Android tutorial - Android Media Player - android app development - android studio - android development tutorial
Learn android - android tutorial - Android media player - android examples - android programs
Android Media Player:
- Android provides many ways to control playback of audio/video files and streams. One of this way is through a class called MediaPlayer.
- Android is providing MediaPlayer class to access built-in mediaplayer services like playing audio,video etc.
- In order to use MediaPlayer, we have to call a static Method create () of this class. This method returns an instance of MediaPlayer class. Its syntax is as follows −
- The second parameter is the name of the song that you want to play. You have to make a new folder under your project with name raw and place the music file into it.
- Once you have created the Mediaplayer object you can call some methods to start or stop the music. These methods are listed below.
- On call to start() method, the music will start playing from the beginning. If this method is called again after the pause() method, the music would start playing from where it is left and not from the beginning.
- In order to start music from the beginning, you have to call reset() method. Its syntax is given below.
- The android.media.MediaPlayer class is used to control the audio or video files.
Methods of MediaPlayer class
- There are many methods of MediaPlayer class. Some of them are as follows:
|public void setDataSource(String path)||sets the data source (file path or http url) to use.|
|public void prepare()||prepares the player for playback synchronously.|
|public void start()||it starts or resumes the playback.|
|public void stop()||it stops the playback.|
|public void pause()||it pauses the playback.|
|public boolean isPlaying()||checks if media player is playing.|
|public void seekTo(int millis)||seeks to specified time in miliseconds.|
|public void setLooping(boolean looping)||sets the player for looping or non-looping.|
|public boolean isLooping()||checks if the player is looping or non-looping.|
|public void selectTrack(int index)||it selects a track for the specified index.|
|public int getCurrentPosition()||returns the current playback position.|
|public int getDuration()||returns duration of the file.|
|public void setVolume(float leftVolume,float rightVolume)||sets the volume on this player.|
- Let's write the code of to play the audio file. Here, we are going to play maine.mp3 file located inside the sdcard/Music directory.
Android MediaPlayer Example of controlling the audio
- Let's see a simple example to start, stop and pause the audio play.
- Drag three buttons from pallete to start, stop and pause the audio play. Now the xml file will look like this:
- Let's write the code to start, pause and stop the audio player.