I am trying to make a small app to practice that consists of a start activity and an activity to select an audio and play it. To select the audio I use:
btnCambiarAudio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Audio "), COD_SONIDO);
}
In the onActivityResult :
case COD_SONIDO:
Uri mUri=data.getData();
String stringUriAudio= data.getDataString();
//String stringUriAudio= mUri.toString();
SharedPreferences datosGuardados = getSharedPreferences("datosMarcos",MODE_PRIVATE);
SharedPreferences.Editor editor = datosGuardados.edit();
editor.putString(nombreAudioMarco, data.getDataString());
editor.apply();
I have also tried the commented instruction. As you can see, I receive the route of the selected audio and the storage using SharePreferences .
Then through another button I play the selected audio.
SharedPreferences datosGuardados = getSharedPreferences("datosMarcos",MODE_PRIVATE);
//obtiene la ruta guardada del archivo de audio seleccionado y vinculada al marco.
String audioMarco = datosGuardados.getString(nombreAudioMarco, "NULL");
Uri uriAudio= Uri.parse(audioMarco);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(getApplicationContext,uriAudio);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "fallo en la reproduccion");
}
}
else {
Toast.makeText(getApplicationContext(), "no hay archivo de audio vinculado", Toast.LENGTH_LONG).show();
}
First I recover the path of the selected audio in the string saved with SharedPreferences , then I create a Uri , and I use it to play the audio with MediaPlayer .
In principle it works, that is, from the activity of the start step to the selection activity, I select an audio, and when I give the play, it works, it reproduces the audio without problems and I also stop it without problems.
The problem, and what I do not understand, and I have been looking for and testing for days, is that if I go from the selection activity to the start activity, and return to the selection activity, it does not work anymore, it gives this error:
D / MediaPlayer: Could not open file on client side, trying server side
E / MediaPlayer: Unable to create media player
And if I re-select the audio and reproduce it, it works again.
In principle, if the route stored in the sharedpreferences works after selecting the audio, it should work when I leave and return to the activity.
I think it may be something of permission, but the audio that I select is in the internal memory, and in theory it does not need to give any special permission.
As information, add, that the tests were made in a physical device, a sony m2, with lollipop (v 5.1.1) .
Thank you.