How to stop the media player, android

I created a list of songs by clicking on a song that I can play using MedaiPlayer. While one song is playing, if the user clicks on another song, I stop the media player and start the player again. But I get an invalid exception in reset (). Here is the code where I get the exception. How to stop the player? also why am I getting this exception. How to avoid this?

public void stopPlayer() { try { if (player != null) { // Log.e("Trying to Stop "," Player "); player.stop(); player.release(); player.reset();// causes IllegalstateException player = null; } } catch (Exception e) { player = null; playerStatus = false; e.printStackTrace(); } } 
+7
source share
4 answers

try the following:

 player.reset(); player.release(); 

and also look at the state diagram of the media player.

+8
source

If you want to play again, use player.reset() , player.release() means it frees the player object, so you need to reinitialize the player. So use reset() first and then release() . release() used when your player’s object is no longer running. When your activity destroys the release() method, which will be used for good practice.

Whenever you want to stop him:

 if(player!=null) { if(player.isPlaying()) player.stop(); player.reset();//It requires again setDataSource for player object. } 

Whenever your player is no longer needed:

 if(player!=null) { if(player.isPlaying()) player.stop(); player.reset();//It requires again setDataSource for player object. player.release(); player=null; // fixed typo. } 
+5
source

Although the accepted answer works, this is the best way to complete the task.

 private void stopSong() { if(mediaPlayer!=null) { if(mediaPlayer.isPlaying()) { mediaPlayer.reset();// It requires again setDataSource for player object. mediaPlayer.stop();// Stop it mediaPlayer.release();// Release it mediaPlayer = null; // Initialize it to null so it can be used later } } } 
+3
source

Are you planning to use the player again, or have you done it with the player? If you are done with the player, call release (), not reset (). If you plan to reuse the player, call reset () and do not release ().

reset () resets the player to an uninitialized state. release () releases all resources associated with the player.

0
source

All Articles