Android Base64 Audio File Encode / Decode

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-08 04:29:09

问题


Doing: I am currently recording voice and saving it as a file in sdCard which is running playing fine in MediaPlayer.

What i want: When i encode this file intoBase64 and send to server, everything goes fine. But When i decode the Base64 String into audio.m4a file, it is not running in MediaPlayer.

I had tried .m4a , .wav but all in vain. The problem is in encoding. Because when i decode a file sent from the same iOS app, it runs fine in 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


回答1:


The problem is before relasing audio i was converting audio into Base64 String thats why Decoded file is corrupt !! Cheers



来源:https://stackoverflow.com/questions/36307464/android-base64-audio-file-encode-decode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!