wagohn
wagohn

Reputation: 93

Using Mediaplayer to replay the same file

Im hoping you can provide some guidance. I created a 'final' instance of a mediaplayer (mp1) and on a button click it plays a mp3 file. I then need to stop the file when I click a second button. This works fine until I try to play the file again - nothing happens. I think that because the mp1 instance is 'final', when I stop it, it stops for good until I relaunch the app. I dont want to pause the file, I want to stop it and then restart it afresh. Any ideas welcome. I tried putting the mp1 creation within the button. This worked until the app crashed - probably because multiple mediaplayer creations used all the device memory?

Thanks!!!

// const mediaplayer
mp1 = MediaPlayer.create(getApplicationContext(), R.raw.mysound);

...

// in button 1
if (radSound1.isChecked()) {
               radSound2.setChecked(false); // ...set radiobutton 2 to false
                mp1.start();                 // ...play the mp3 file
               }

...


// in button 2
if (mp1 != null){
                  mp1.reset();
                   //mp1.setDataSource();
                   // mp1.prepare(); 
              }

Upvotes: 4

Views: 5132

Answers (1)

Erol
Erol

Reputation: 6526

Follow the state diagram here. stop() stops playing and puts you in stopped state. Before starting to play for the next time, you should call prepare() and then start() again.

So in button 1, you should call start() and in button 2, you should call stop() and prepare(). The initialization is fine, do it once and keep it outside the buttons.

Also accept answers to your questions including this so that people like me will be more motivated to reply to them in the future.

Upvotes: 13

Related Questions