I have a function that receives a byte array and saves it in "file.mp3", the "file.mp3" is saved in the cell phone but can not be opened.
I used MediaPlayer following this post Android - Playing mp3 from byte[] but it kills the application by doing it in this way, instead of temporarily creating the file, i directly save it in the phone, but the "file.mp3" does not work.
Following this other post Play sound from array on Android i test that it works if it takes a random array of bytes, but when i use my array of bytes, it also does not work.
I have this function:
@GET("tts/talk/{text}")
Call<ResponseBody> sendText(@Path("text") String text);
I send a text to my REST API and i get an array of bytes through ResponseBody
following this way:
public void sendText(String text){
Call<ResponseBody> call = ttsService.sendText(text);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful()){
try {
downloadMp3(response.body().bytes());
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, "Error connection", Toast.LENGTH_SHORT).show();
}
}
}
The function downloadMp3(response.body ().bytes())
, it receives an array of bytes and saves it in file.mp3 directly on the phone:
private void downloadMp3(byte[] mp3SoundByteArray) {
try {
File file = new File( Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"audio.mp3"
);
FileOutputStream fos = new FileOutputStream(file);
fos.write(mp3SoundByteArray);
fos.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
Is this way of saving the array of bytes okay? Is there another way to save an array of bytes in an file.mp3 or any audio file or must there be a processing of that array of bytes before?