How to Create a MediaPlayer for an Audio Resource
MediaPlayer.create (Context context, int resid) was added in API Level 1Convenience method to create a MediaPlayer for a given resource id. On success, prepare() will already have been called and must not be called again.
When done with the MediaPlayer, you should call release(), to free the resources. If not released, too many MediaPlayer instances will result in an exception.
1. Add the Audio File to your Android Project. For this example, name your audio file myaudio.ogg (or any compatible audio extension.)
2. Declare and Initialize a MediaPlayer, named myMediaPlayer, initialized to null.
3. In the MainActivity.java file, add the below line of code to the onCreate method. This will instantiate an instance of MediaPlayer. Replace myaudio with your audio name. The extension is not included below. (Example: Use myaudio. Do NOT use myaudio.ogg)
myMediaPlayer = MediaPlayer.create(this, R.raw.myaudio);
4. Add the below import to the import section.
import android.widget.Toast;
5. Now test to see if myMediaPlayer was created successfully. Add this code to the onCreate method.
if (myMediaPlayer != null) { //make sure media player was created
Toast.makeText(this, "myMediaPlayer was created successfully!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "myMediaPlayer not Created :(", Toast.LENGTH_SHORT).show();
}
myMediaPlayer = MediaPlayer.create(this, R.raw.myaudio);
4. Add the below import to the import section.
import android.widget.Toast;
5. Now test to see if myMediaPlayer was created successfully. Add this code to the onCreate method.
if (myMediaPlayer != null) { //make sure media player was created
Toast.makeText(this, "myMediaPlayer was created successfully!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "myMediaPlayer not Created :(", Toast.LENGTH_SHORT).show();
}
6. Compile and run!
Next Recommended Article: MediaPlayer.start() - How to Start Playing an Audio File on a MediaPlayer
Next Recommended Article: MediaPlayer.start() - How to Start Playing an Audio File on a MediaPlayer