Skip to content Skip to sidebar Skip to footer

How To Play/stop/play Again Using Mediaplayer

I have a button when clicked it plays an audio, and while it is playing I can pause it and replay it again and so forth. I have a shake event, where I want to play the audio on sha

Solution 1:

First of all create the MediaPlayer in onCreate of the context and not in some listener, and don't forget to release it when done, since it consumes a lot of resources,

mediaPlayer.release();
mediaPlayer = null;

Next thing, stop the audio using the stop() function instead of the pause() on completion of the song.

Steps

If you are using a service/activity to play a video create a MediaPlayer instance before it's usage begins, likely in onCreate.

Later use that instance to play/pause/stop the media.

In the onStop of the Service/Activity release the MediaPlayer instance.

Update your playMusic() function to use the MediaPlayer instance you just created, also in the listener use stop() instead of pause()

To change track of an existing MediaPlayer instance

You can use this:

Stringpath= getExternalFilesDir(null).toString()+"/";

mMediaPlayer.setDataSource(path + mediafile);

Link: Changing data source for audio playback using existing MediaPlayer?

Post a Comment for "How To Play/stop/play Again Using Mediaplayer"