简体   繁体   English

Android Base64 音频文件编码/解码

[英]Android Base64 Audio File Encode / Decode

Doing: I am currently recording voice and saving it as a file in sdCard which is running playing fine in MediaPlayer.正在做:我目前正在录制语音并将其保存为 sdCard 中的文件,该文件在 MediaPlayer 中运行良好。

What i want: When i encode this file intoBase64 and send to server, everything goes fine.我想要什么:当我将此文件编码为 Base64 并发送到服务器时,一切正常。 But When i decode the Base64 String into audio.m4a file, it is not running in MediaPlayer.但是当我将 Base64 字符串解码为 audio.m4a 文件时,它没有在 MediaPlayer 中运行。

I had tried .m4a , .wav but all in vain.我曾尝试过 .m4a 、 .wav 但都是徒劳的。 The problem is in encoding.问题在于编码。 Because when i decode a file sent from the same iOS app, it runs fine in MediaPlayer.因为当我解码从同一个 iOS 应用程序发送的文件时,它在 MediaPlayer 中运行良好。

I know its very basic and alot of help is there to encode decode but nothing is working.我知道它非常基本,并且在编码解码方面有很多帮助,但没有任何效果。 Following is my approach:以下是我的做法:

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);
}

}     

And Decoding in the following way:并按以下方式解码:

 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();
}


}     

Please point if i am doing anything wrong.如果我做错了什么,请指出。 Thanks谢谢

The problem is before relasing audio i was converting audio into Base64 String thats why Decoded file is corrupt !!问题是在释放音频之前,我将音频转换为Base64 String这就是解码文件损坏的原因! Cheers干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM