1

我正在尝试编码(base64)一个 mp3 文件,将其保存到数据库中,然后检索它并对其进行解码并播放该文件。我已经输入了以下代码,但它似乎不起作用。我可以做任何修复以使其正常工作吗?

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javazoom.jl.player.Player;

import org.apache.commons.codec.binary.Base64;

public class ReadAudioFile {
    public static void main(String[] args) throws Exception {
        String file = "C:\\Users\\Mukkra01\\Downloads\\apple.mp3";
        InputStream byteInputStream = new FileInputStream(file);
        System.out.println(Base64.encodeBase64(inputStreamToByteArray(byteInputStream)));
        byte[] decodeFile = Base64.decodeBase64(Base64.encodeBase64(inputStreamToByteArray(byteInputStream)));
        play(decodeFile);
    }

    public static byte[] inputStreamToByteArray(InputStream inStream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = inStream.read(buffer)) > 0) {
            baos.write(buffer, 0, bytesRead);
        }
        return baos.toByteArray();
    }

    public static void play(byte[] decodeFile) {
        try {
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(decodeFile);
            //BufferedInputStream buffer = new BufferedInputStream(new FileInputStream("C:\\Users\\Mukkra01\\Downloads\\apple.mp3"));
            Player player = new Player(byteInputStream);
            player.play();
        } catch (Exception e) {
            System.out.println(e);
        }

    }
}
4

0 回答 0