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
Author by
JDS
Updated on June 04, 2022Comments
-
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 infileM.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 over 11 yearsYep 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 over 10 yearsi am sorry i gave a downvote,now i cant change it...please edit ur answer and notify me so that i can upvote..
-
ahmadPH about 3 yearsYou can also try
MediaPlayer.create(context, Uri.parse(path))
, which is more succinct than instantiating theMediaPlayer
, then setting its data source, and then callingprepare
.