问题
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