简体   繁体   中英

Android code to play .wav files located in res/raw - weird errors

I've been stuck on this particular problem for a while now, and it's something that should be really simple so it's annoying.. I must be misusing the Android API somehow?

Here is the code:

  try {
  String packageName = getPackageName(); 
  int resID = getResources().getIdentifier( "filename" , "raw" , packageName ); //in res/raw folder I have filename.wav audio file
  mp.setDataSource("android.resource://" + packageName + "/" + resID);
  mp.prepare();
  mp.start();
} catch (Exception e) {
  Toast.makeText(PlayScreen.this, e.toString(), Toast.LENGTH_LONG).show(); 
}

The toast message I see says:

java.io.IOException: Prepare failed.: status=0xFFFFFFFC

In eclipse logcat I see:

MediaPlayer Error (-4 -4)

Much thanks to anyone who can help with this... I just want to play my wav files darn it!

Try using a FileDescriptor instead:

String packageName = getPackageName(); 
int resID = getResources().getIdentifier( "filename" , "raw" , packageName );
AssetFileDescriptor afd = getResources().openRawResourceFd(resId);
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();
afd.close();

That's what I always do and it's safer to do it that way rather than hardcoding a path.

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