简体   繁体   中英

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

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, ie 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.

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

i think that should be like that as sample at http://en.kuma-de.com/blog/2011-11-14/341

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM