Javatpoint Logo
Javatpoint Logo

Kotlin Android Media Player

MediaPlayer is a class that is used to control the playback of audio/video files and streams.

The android.media.MediaPlayer class is used to control the audio or video files. It accesses the built-in media player services such as playing audio, video, etc. To use the MediaPlayer class, we have to call the create the instance of it by calling the create() method of this class.

Methods of MediaPlayer class

There are several methods of MediaPlayer class available. Some of them are as follows:

Method Description
public void setDataSource(String path) It sets the data source (file path or http url) to use.
public void prepare() It 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() It checks if the media player is playing.
public void seekTo(int millis) It seeks to specified time in milliseconds.
public void setLooping(boolean looping) It sets the player for looping or non-looping.
public boolean isLooping() It 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() It returns the current playback position.
public int getDuration() It returns duration of the file.
public void setVolume(float leftVolume,float rightVolume) It sets the volume on this player.

Example of Android MediaPlayer with SeekBar

In this example, we will create a Media Player with playback control functionality such as play, pause, and stop. We also integrate the SeekBar to show the progress level of the media player.

activity_main.xml

In the activity_main.xml layout file, we add the Buttons to control media playback, TextView to display the time duration of song and SeekBar to show the progress level of the media file.

MianActivity.kt

The instance of MediaPlayer class is created using the MediaPlayer.create() method. In this example, we are reading the media file from the raw directory. The MediaPlayer.start() method starts playing media file, MediaPlayer.pause() method pause media and Media.stop() method stops playing media file.

Output:


Kotlin Android Media Player Kotlin Android Media Player
Kotlin Android Media Player





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA