Android: playing audio files in /res/raw by file name

10,354
MediaPlayer player = new MediaPlayer();
String path = "android.resource://" + getPackageName() + "/raw" + filename;
try {
     player.setDataSource(context, Uri.parse(path));
     player.prepare();
     player.start();
} catch (IOException e) {
     e.printStackTrace();
}

try it with or without the extention ".mp3"

hope i could help you

Share:
10,354
JDS
Author by

JDS

Updated on June 04, 2022

Comments

  • JDS
    JDS almost 2 years

    In my application's /res/raw/ folder, I have: file1.ogg file2.ogg ... fileN.ogg

    In a local database, I have the references to the file names, i.e. file1 file2 ... fileN.

    Given one of those strings, say fileM, how can I play the audio contained in fileM.ogg? Looking for the relevant Java code here.

    Here's what I looked at so far:

    String name = "plumber";
    String link = "/res/raw/" + name + ".ogg";
    
    try {
        mp.setDataSource(link); //earlier: mp = new MediaPlayer();
        mp.prepare();
        mp.start();
    } catch (Exception e) {
        Toast.makeText(PlayScreen.this, "ERROR: audio player not working.", Toast.LENGTH_LONG).show(); 
    }
    

    I get the error message in the toast. Also I've tried the link string without "/res/raw" in it.

    Thank you.

  • JDS
    JDS over 11 years
    Yep I think that's the right idea. I found this website to be helpful as well: en.kuma-de.com/blog/2011-11-14/341
  • Ankit Srivastava
    Ankit Srivastava over 10 years
    i am sorry i gave a downvote,now i cant change it...please edit ur answer and notify me so that i can upvote..
  • ahmadPH
    ahmadPH about 3 years
    You can also try MediaPlayer.create(context, Uri.parse(path)) , which is more succinct than instantiating the MediaPlayer, then setting its data source, and then calling prepare.