[ACCEPTED]-base64 encode audio file and send as a String then decode the String-android
Accepted answer
You're heavily mixing String
s and byte[]
s. Don't do 9 that. If you want to encode a byte[]
to a String
, use 8 Base64.encodeToString()
, instead of encoding to bytes and then creating 7 a string.
If I try to save decodedBytes using 6 os.write(decodedBytes) it works but not 5 when converted to a String and getBytes() is 4 used.
Calling new String(byte[])
does not do what you think 3 it does.
Likewise use Base64.decode(String, int)
to decode the string.
Something 2 like this (not tested):
File file = new File(Environment.getExternalStorageDirectory() + "/hello-4.wav");
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);
Utilities.log("~~~~~~~~ Encoded: ", encoded);
byte[] decoded = Base64.decode(encoded, 0);
Utilities.log("~~~~~~~~ Decoded: ", Arrays.toString(decoded));
try
{
File file2 = new File(Environment.getExternalStorageDirectory() + "/hello-5.wav");
FileOutputStream os = new FileOutputStream(file2, true);
os.write(decoded);
os.close();
}
catch (Exception e)
{
e.printStackTrace();
}
But why are you base64 encoding 1 an audio file in the first place?
Decoding base64 string file to .m4a file 1 format
try
{
String audioDataString = "";
BufferedReader jsonReader = new BufferedReader(new InputStreamReader(this.getResources().openRawResource(R.raw.audioBase64File)));
StringBuilder jsonBuilder = new StringBuilder();
for (String line = null; (line = jsonReader.readLine()) != null; ) {
jsonBuilder.append(line).append("");
}
audioDataString = jsonBuilder.toString();
byte[] decoded = Base64.decode(audioDataString, Base64.DEFAULT);
try {
File file2 = new File(Environment.getExternalStorageDirectory() + "/faakhir_testAudio.m4a");
FileOutputStream os = new FileOutputStream(file2, true);
os.write(decoded);
os.close();
} catch (Exception e) {
e.printStackTrace();
}
} catch(Exception e){
e.printStackTrace();
}
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.