Android stop media player from another Activity

Android - MediaPlayer


Advertisements

Previous Page
Next Page

Android provides many ways to control playback of audio/video files and streams. One of this way is through a class called MediaPlayer.

Show

Android is providing MediaPlayer class to access built-in mediaplayer services like playing audio,video e.t.c. 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

MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.song);

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.

mediaPlayer.start(); mediaPlayer.pause();

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.

mediaPlayer.reset();

Apart from the start and pause method, there are other methods provided by this class for better dealing with audio/video files. These methods are listed below

Sr.NoMethod & description
1

isPlaying()

This method just returns true/false indicating the song is playing or not

2

seekTo(position)

This method takes an integer, and move song to that particular position millisecond

3

getCurrentPosition()

This method returns the current position of song in milliseconds

4

getDuration()

This method returns the total time duration of song in milliseconds

5

reset()

This method resets the media player

6

release()

This method releases any resource attached with MediaPlayer object

7

setVolume(float leftVolume, float rightVolume)

This method sets the up down volume for this player

8

setDataSource(FileDescriptor fd)

This method sets the data source of audio/video file

9

selectTrack(int index)

This method takes an integer, and select the track from the list on that particular index

10

getTrackInfo()

This method returns an array of track information

Example

Here is an example demonstrating the use of MediaPlayer class. It creates a basic media player that allows you to forward, backward, play and pause a song.

To experiment with this example, you need to run this on an actual device to hear the audio sound.

StepsDescription
1You will use Android studio IDE to create an Android application under a package com.example.sairamkrishna.myapplication.
2Modify src/MainActivity.java file to add MediaPlayer code.
3Modify the res/layout/activity_main to add respective XML components
4Create a new folder under MediaPlayer with name as raw and place an mp3 music file in it with name as song.mp3
5Run the application and choose a running android device and install the application on it and verify the results

Following is the content of the modified main activity file src/MainActivity.java.

package com.example.sairamkrishna.myapplication; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.util.concurrent.TimeUnit; public class MainActivity extends Activity { private Button b1,b2,b3,b4; private ImageView iv; private MediaPlayer mediaPlayer; private double startTime = 0; private double finalTime = 0; private Handler myHandler = new Handler();; private int forwardTime = 5000; private int backwardTime = 5000; private SeekBar seekbar; private TextView tx1,tx2,tx3; public static int oneTimeOnly = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); b1 = (Button) findViewById(R.id.button); b2 = (Button) findViewById(R.id.button2); b3 = (Button)findViewById(R.id.button3); b4 = (Button)findViewById(R.id.button4); iv = (ImageView)findViewById(R.id.imageView); tx1 = (TextView)findViewById(R.id.textView2); tx2 = (TextView)findViewById(R.id.textView3); tx3 = (TextView)findViewById(R.id.textView4); tx3.setText("Song.mp3"); mediaPlayer = MediaPlayer.create(this, R.raw.song); seekbar = (SeekBar)findViewById(R.id.seekBar); seekbar.setClickable(false); b2.setEnabled(false); b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "Playing sound",Toast.LENGTH_SHORT).show(); mediaPlayer.start(); finalTime = mediaPlayer.getDuration(); startTime = mediaPlayer.getCurrentPosition(); if (oneTimeOnly == 0) { seekbar.setMax((int) finalTime); oneTimeOnly = 1; } tx2.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) finalTime), TimeUnit.MILLISECONDS.toSeconds((long) finalTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) finalTime))) ); tx1.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) startTime), TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) startTime))) ); seekbar.setProgress((int)startTime); myHandler.postDelayed(UpdateSongTime,100); b2.setEnabled(true); b3.setEnabled(false); } }); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(getApplicationContext(), "Pausing sound",Toast.LENGTH_SHORT).show(); mediaPlayer.pause(); b2.setEnabled(false); b3.setEnabled(true); } }); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int temp = (int)startTime; if((temp+forwardTime)<=finalTime){ startTime = startTime + forwardTime; mediaPlayer.seekTo((int) startTime); Toast.makeText(getApplicationContext(),"You have Jumped forward 5 seconds",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(),"Cannot jump forward 5 seconds",Toast.LENGTH_SHORT).show(); } } }); b4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int temp = (int)startTime; if((temp-backwardTime)>0){ startTime = startTime - backwardTime; mediaPlayer.seekTo((int) startTime); Toast.makeText(getApplicationContext(),"You have Jumped backward 5 seconds",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(),"Cannot jump backward 5 seconds",Toast.LENGTH_SHORT).show(); } } }); } private Runnable UpdateSongTime = new Runnable() { public void run() { startTime = mediaPlayer.getCurrentPosition(); tx1.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) startTime), TimeUnit.MILLISECONDS.toSeconds((long) startTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS. toMinutes((long) startTime))) ); seekbar.setProgress((int)startTime); myHandler.postDelayed(this, 100); } }; }

Following is the modified content of the xml res/layout/activity_main.xml.

In the below code abcindicates the logo of tutorialspoint.com