The problem I am trying to solve is in an activity that needs to play back audio files. Most of the files will be user created (and saved into external storage), and therefore played with the following code (based on Google's example code):
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(filename);
mPlayer.prepare();
mPlayer.start();
Some of the audio files, though, are going to be included with the app, are usually played with the following code:
MediaPlayer mPlayer = MediaPlayer.create(getBaseContext(), R.raw.filename);
mPlayer.prepare();
mPlayer.start();
The issue is that I would like to be able to play the audio files in the raw folder in the same way that I am playing the user created files since I don't necessarily know which will be needed. I tried tried to get the URI of the audio file in the raw folder and play it with the following code:
Uri uri = Uri.parse("android/resource://com.my.package/" + R.raw.filename);
MediaPlayer mPlayer = new MediaPlayer();
mPlayer.setDataSource(uri.toString());
mPlayer.prepare();
mPlayer.start();
But nothing happens. No error messages, no playing audio.
I outlined what I thought was the simplest solution, but I am willing to go another route if it accomplishes the task. Any assistance is greatly appreciated.
I've managed to get it working, here is the code I used.
mMediaPlayer = new MediaPlayer();
Uri mediaPath = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.filename);
try {
mMediaPlayer.setDataSource(getApplicationContext(), mediaPath);
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
I see two problems I see with your code. The first is that "android/resource" needs to become "android.resource"
The second is that setDataSource(String) won't work in this case due to the fact that you need context to use raw files as otherwise it tries to open the file incorrectly. (See the top answer in MediaPlayer.setDataSource(String) not working with local files)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With