Mediaplayer plays twice

2019-07-20 04:00发布

问题:

I have a media player but when another file is selected it continues to play the old file and new one so it is playing two files at once here is my onCreate method

private MediaPlayer mediaplayer = new MediaPlayer();
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.songplaying);

// Getting Our Extras From Intent
 Bundle names = getIntent().getExtras();

// Getting Specific Data

 path = names.getString("pathkeyword");


 //Start Player
 try {
    playAudio(path);

} catch (Exception e) {
   e.printStackTrace();

}

and this is the method that plays the audio

 private void playAudio(String url) throws Exception{

  mediaplayer.release();
  mediaplayer.setDataSource(url);
  mediaplayer.prepare();
  mediaplayer.start();

回答1:

When you are start to play the song ,check it is playing or not and stop it if it is currently playing.

     if(player.isPlaying())
      {  
        mediaplayer.stop();
       } 
        mediaplayer.reset();

  mediaplayer.setDataSource(url);
  mediaplayer.prepare();
  mediaplayer.start();

no need to release the player.player.release() used only when player no longer needed .

And you have to use stop() and release() methods whenever activity destroys.Otherwise so many players are running in background.



回答2:

Try to add this to oncreate method so you will be able to prevent the new creation of audio

Mediaplayer M = Mediaplayer.create(this,R.row.audio file)

and make a new function like

void my function {
    // call it here 
    m.start();
}