Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Media Player Restart Audio After Calling Stop

I'm able to stream audio and stop it without any problem, but when I try to start it again after stop, it doesn't start and I get an IllegalState exception.

Here is what I'm doing:

Start Playing

mediaPlayer.setDataSource(PATH);
mediaPlayer.prepare();
mediaPlayer.start();

Stop Playing

mediaPlayer.stop

Now, if I want to start playing again the same media, what will I have to do?

*PATH is the URL of a continuous running radio station.

like image 643
Sharj Avatar asked Dec 20 '10 04:12

Sharj


People also ask

What is MediaPlayer in Android?

android.media.MediaPlayer. MediaPlayer class can be used to control playback of audio/video files and streams. MediaPlayer is not thread-safe. Creation of and all access to player instances should be on the same thread. If registering callbacks, the thread must have a Looper.

How do I reset my media player on Android?

Just use pause to stop, followed by seekTo(0) before restarting: mediaPlayer. seekTo(0); mediaPlayer.

How to play audio using Media Player in Android?

Start/Pause the playback: After loading the media file, you can start playing the media file by using the start() method. Similarly, you can pause the playing media file by using the pause() method. Stop the playback: You can stop playback by using the reset() method.


3 Answers

In case you don't have access to the data source in the current scope, you can do:

mp.pause();
mp.seekTo(0);

Then when you do

mp.start();

play will start from the beginning again.

I needed this because I had a button that toggled playing. I had a togglePlayer method in which the datasource was out of scope.

like image 55
abalter Avatar answered Nov 15 '22 22:11

abalter


Add this:

mp.reset();
mp.setDataSource(MEDIA_PATH);
mp.prepare();
mp.start();
like image 28
Sandy Avatar answered Nov 15 '22 20:11

Sandy


you can check the state diagram of mediaplayer http://developer.android.com/reference/android/media/MediaPlayer.html after the mediaplayer stopped, must call prepare, when prepared,and then you can call start method.

like image 38
Gao Yuesong Avatar answered Nov 15 '22 21:11

Gao Yuesong