user3375559
user3375559

Reputation: 1

Android MediaPlayer not working after multiple starts

I am having trouble with MediaPlayer. In the enclosed code, when a button is touched, a voice cue is activated when the option to do so is selected. However, the voice works for approximately 31 times and then the sound goes off. Using the .release() method (which I have commented out for now) causes the sound to not work at all.

How can I correct this function?

Thank You

.... 
import android.media.MediaPlayer;
....
MediaPlayer mp = null;
........

//  Causes the name of the appropriate cell to be announced

    public void sayCellName() {
        if(voiceChoice == false) return;
        else{
            switch(cellName){             
            case 1:
                mp = MediaPlayer.create(this, R.raw.poly);
                break;
            case 2:
                mp = MediaPlayer.create(this, R.raw.lymph);
                break;
            case 3:
                mp = MediaPlayer.create(this, R.raw.mono);
                break;
            case 4:
                mp = MediaPlayer.create(this, R.raw.eo);
                break;
            case 5:
                mp = MediaPlayer.create(this, R.raw.baso);
                break;
            case 6:
                mp = MediaPlayer.create(this, R.raw.band);
                break;
            default:
                break;
            } // end switch statement
        } // end else statement;
        mp.start();
//      mp.release();
    } // end of sayCellName
} // end of main

Upvotes: 0

Views: 92

Answers (2)

tiguchi
tiguchi

Reputation: 5410

The Android OS has a hard-coded limit of audio track resources that may play back sound simultaneously. As it so happens that limit is 32 tracks that have to be shared by all running applications. What you are doing is wasting these tracks by creating fresh MediaPlayers on each button click without releasing them.

For your scenario you should probably create and reuse a single MediaPlayer instance and release it when your Activity stops. It is possible to reset a MediaPlayer and set a different stream data source afterwards.

Upvotes: 1

meda
meda

Reputation: 45500

You have to release the player OnPause or OnDestroy method.

   @Override
   public void onPause() {
       if (mp!= null) mp.release();
   }

Upvotes: 0

Related Questions