Android Base64音频文件编码/解码

时间:2016-03-30 11:28:28

标签: java android base64

正在执行:我正在录制语音并将其保存为sdCard中的文件,该文件在MediaPlayer中正常运行。

我想要的是什么:当我将此文件编码为Base64并发送到服务器时,一切都很顺利。但是当我将Base64字符串解码为audio.m4a文件时,它没有在MediaPlayer中运行。

我曾尝试过.m4a,.wav,但都是徒劳的。 问题在于编码。因为当我解码从同一iOS应用程序发送的文件时,它在MediaPlayer中运行良好。

我知道它非常基本,很多帮助是编码解码,但没有任何工作。以下是我的方法:

private void encodeAudio(String selectedPath) {

byte[] audioBytes;
try {

    // Just to check file size.. Its is correct i-e; Not Zero
    File audioFile = new File(selectedPath);
    long fileSize = audioFile.length();

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    FileInputStream fis = new FileInputStream(new File(selectedPath));
    byte[] buf = new byte[1024];
    int n;
    while (-1 != (n = fis.read(buf)))
        baos.write(buf, 0, n);
    audioBytes = baos.toByteArray();

    // Here goes the Base64 string
    _audioBase64 = Base64.encodeToString(audioBytes, Base64.DEFAULT);

} catch (Exception e) {
    DiagnosticHelper.writeException(e);
}

}     

以下列方式解码:

 private void decodeAudio(String base64AudioData, File fileName, String path, MediaPlayer mp) {

try {

    FileOutputStream fos = new FileOutputStream(fileName);
    fos.write(Base64.decode(base64AudioData.getBytes(), Base64.DEFAULT));
    fos.close();

    try {

        mp = new MediaPlayer();
        mp.setDataSource(path);
        mp.prepare();
        mp.start();

    } catch (Exception e) {

        DiagnosticHelper.writeException(e);

    }

} catch (Exception e) {
    e.printStackTrace();
}


}     

如果我做错了,请指出。 谢谢

1 个答案:

答案 0 :(得分:0)

问题出在重新启动音频之前我将音频转换为Base64 String这就是为什么解码文件已损坏!!干杯