In MediaPlayer.create method an id to a Raw file can be used but how to use that in setDataSource method?
android.media.MediaPlayer. MediaPlayer class can be used to control playback of audio/video files and streams. MediaPlayer is not thread-safe. Creation of and all access to player instances should be on the same thread. If registering callbacks, the thread must have a Looper.
So instead of calling MediaPlayer directly, MediaPlayerWrapper is used, which internally updates StateMachine and exposes getState() method.
Just use pause to stop, followed by seekTo(0) before restarting: mediaPlayer. seekTo(0); mediaPlayer.
Refer to the source android.media.MediaPlayer
AssetFileDescriptor afd = context.getResources().openRawResourceFd(resid); if (afd == null) return; mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength()); afd.close();
You may want to add try-catch to the block.
paraphrasing @Kartik's answer here Get URI of .mp3 file stored in res/raw folder in android
If you want to get any resource URI then there are two ways :
Syntax : android.resource://[package]/[res type]/[res name]
Example : Uri.parse("android.resource://com.my.package/drawable/icon");
Syntax : android.resource://[package]/[resource_id]
Example : Uri.parse("android.resource://com.my.package/" + R.drawable.icon);
These were the examples to get the URI of any image file stored in drawable folder. Similarly you can get URIs of res/raw folder.
IMO the second way would be preferred as renaming the resource etc can be easily refactored.
Set the data source like so:
CONSTANTS.RES_PREFIX = "android.resource://com.my.package/"
mp.setDataSource(getApplicationContext(), Uri.parse(CONSTANTS.RES_PREFIX + R.raw.id));
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