After reading "Media Playback" and "MediaPlayer" android documentations I'm still confused and need experienced advice about setDataSource overloaded method.
I am using MediaPlayer
in a Service
component in my Project that is going to be a foregroundService while playing music. I have my music file(.mp3) in res/raw
folder of my apk.
To start playing, I know I have to prepare the MediaPlayer object. Because Services in android applications by default uses single process and main thread, I don't want my users get ANR
while MediaPlayer prepares itself(think if media file in raw folder has a big size).
Then I use prepareAsync
instead of prepare
(Sync). So I can not use:
mp = MediaPlayer.create(context, R.raw.myfile);
Because this already calls prepare()
internally but not prepareAsync()
.
So basically i have two options(two from four):
Uri myUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.myfile);
mp.setDataSource(context, myUri);
or
AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.myfile);
mp.setDataSource(fd.getFileDescriptor());
afd.close();
after using one of them I can simple use:
mp.prepareAsync();
And finally my questions arise that "including these different methods, which one is the best option? Are there any benefits one over the other? Do i missing something?"