简体   繁体   中英

Mediaplayer stopped playing my sound - Android studio

So i was trying to do Onclick for all the buttons... whenever the user click some butto it go to OnClickButton , and then play some sound .. for button1 it will play mp1 for button 2 play sound2 .... so everything work fine but when I clicking a lot on the buttons after a while the sound just stopped be played .. this is the code :

public void OnClick(View v) {


    final MediaPlayer mp1 = MediaPlayer.create(this, R.raw.sound1);
    final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.sound2);
    final MediaPlayer mp3 = MediaPlayer.create(this, R.raw.sound3);
    final MediaPlayer mp4 = MediaPlayer.create(this, R.raw.sound4);

    TextView mytv = (TextView) findViewById(R.id.tvMytimer);
    int id = v.getId();
    if (id == R.id.btComp1 || id==R.id.btUser1)
    {
        mytv.setText("Button 1");
        mp1.start();

    }
    if (id == R.id.btComp2 || id==R.id.btUser2)
    {
        mytv.setText("Button 2");
        mp2.start();

    }
    if (id == R.id.btComp3 || id==R.id.btUser3)
    {
        mytv.setText("Button 3");

        mp3.start();

    }
    if (id == R.id.btComp4 || id==R.id.btUser4)
    {
        mytv.setText("Button 4");

        mp4.start();

    }


}

I allso disable all casual button sound because all I wanted that will be sound is my sounds ..

(disable with setSoundEffectsEnabled(false) 

First of all, don't create a new MediaPlayer in every onClick. That's completely unnecessary. Just create them once when the activity starts.

Second, it doesn't look like you're doing anything with MediaPlayer except call its start method. MediaPlayer has a rather complicated lifecycle you need to observe. See the javadoc to understand what you have to understand to make it work correctly.

If all you want to do is quickly trigger some sounds to play in response to buttons, you should probably instead by using a SoundPool to manage and play all the sounds. I would definitely prefer that over MediaPlayer for what you're trying to do. It's much easier to work with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM