Media Player
Media Player
Android-Media Player
Android provides many ways to control the playback of audio/video files and streams. One of
these ways is through a class called MediaPlayer.
Android provides MediaPlayer class to access built-in media player 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 the MediaPlayer class. Its syntax is as follows −
The second parameter is the name of the song that you want to play. You must make a new
folder under your project with the 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.
mediaPlayer.start();
mediaPlayer.pause();
mediaPlayer.stop();
On the call to start() method, the music will start playing from the beginning. If this method is
called again after the pause() method, the music will start playing from where it is left and not
from the beginning.
Example
Here is an example demonstrating the use of the MediaPlayer class. It creates a basic media
player that allows you to play, pause, and stop a song.
To experiment with this example, you need to run this on an actual device to hear the audio
sound.
Steps Description
You will use Android Studio IDE to create an Android application under a package
1
package com.example.mediaplayer;
Run the application choose a running Android device and install the application on it and
5
verify the results
package com.example.mediaplayer;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button start,pause,stop;
MediaPlayer mp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button)findViewById(R.id.playButton);
pause=(Button)findViewById(R.id.pauseButton);
stop=(Button)findViewById(R.id.stopButton);
//creating media player
mp = MediaPlayer.create(this, R.raw.sound);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.start();
}
});
pause.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.pause();
}
});
stop.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mp.stop();
}
});
}
}