1

I am trying to play an audio file based on a user selection... if the user choose from spinner the second value so the file will be 02.mp3 and if the selection is 153 the file will be 153.mp3

the line of code with the problem is:

mediaPlayer.setDataSource(getApplicationContext(), Uri.parse("android.resource://" + getPackageName() + "/raw/" + dir));

dir = the user selection from the spinner as string, Ex: "023.mp3"

the mp3 files are in the raw folder of the app

the result of the line of code is: android.resource://mypackagename/raw/023.mp3

but the mp3 file not playing...

image link for the error: https://ibb.co/eJS7dv Please help

thank in advance

yossef douieb
  • 146
  • 1
  • 2
  • 12

1 Answers1

0

This method should works:

void playSound(String dir){
String filename = "android.resource://" + this.getPackageName() + "/raw/" + dir;

mp = new MediaPlayer();
try { mp.setDataSource(this,Uri.parse(filename)); } catch (Exception e) {}
try { mp.prepare(); } catch (Exception e) {}
mp.start();
}

edit

can you check that you can play the mp3 on your computer, to check if the file is not corrupted? Or test with the method getIdentifier()

void playSound(String dir){
try { 
 MediaPlayer mp =MediaPlayer.create(getApplicationContext(), getResources().getIdentifier(dir,"raw",getPackageName()));
} catch (Exception e) {}
mp.start();
}

like in this post : MediaPlayer.setDataSource(String) not working with local files

Community
  • 1
  • 1
letroll
  • 1,059
  • 1
  • 14
  • 36