Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Mediaplayer to replay the same file

Tags:

android

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(); 
              }
like image 253
wagohn Avatar asked Dec 15 '22 21:12

wagohn


1 Answers

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.

like image 170
Erol Avatar answered Jan 09 '23 08:01

Erol