I'm using several media player objects to loop some tracks and I want to know that is the difference between using the MediaPlayer.create(resId) versus manually programming the different states, using setDataSource(FileDescriptor) ect.. I'm still new to android so I have no idea.
Java documentation for android.media.MediaPlayer.setDataSource (java.io.FileDescriptor). Portions of this page are modifications based on work created and shared by the Android Open Source Project and used according to terms described in the Creative Commons 2.5 Attribution License. Sets the data source (file-path or http/rtsp URL) to use.
MediaPlayer Class in Android is used to play media files. Those are Audio and Video files. It can also be used to play audio or video streams over the network. So in this article, the things discussed are: Creating a simple audio player using MediaPlayer API.
This class is the primary API for playing sound and video. This class manages audio sources and audio output on a device. Before starting development on your application using MediaPlayer, make sure your manifest has the appropriate declarations to allow use of related features.
The layout of the application consists of three buttons PLAY, PAUSE, and STOP mainly, which is used to control the state of the MediaPlayer instance. Invoke the following code inside the activity_main.xml file to implement the UI.
.create()
is a static method of MediaPlayer
class, whenever you want to call .create()
you have to call it by ClassName.methodName()
like MediaPlayer.create()
while setDataResource()
is a method in MediaPlayer
class it will be call through the instance of MediaPlayer
like
MediaPlayer mp;
mp.setDataResource("your sdCard File Path...");
Now if you use MediaPlayer.create()
you should have audio(mp3) file in your raw
folder under res
. If you don't have raw
folder create one (normally we have to create raw
folder manually in our project) and pass the resId
of that mp3 file in .create()
method like
MediaPlayer mp = MediaPlayer.create(R.raw.mp3FileName);
Second one is setDataResource()
method is used where you want to play audio files through your SDCard
but You need to make sure the path you give to setDataSource() is exactly correct. The best way to do this, instead of hardcoding the reference to '/sdcard/', is to use
android.os.Environment.getExternalStorageDirectory()
MediaPlayer mediaPlayer = new MediaPlayer();
File path = android.os.Environment.getExternalStorageDirectory();
mediaPlayer.setDataSource(path + "/fileName.mp3");
In this way you can get correct path and play your mp3 through SDCard.
Hope this explaination will help you to understand. For more info see MediaPlayer From Android Developer Site
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