媒体播放器在一段时间后停止工作

时间:2017-03-01 12:34:10

标签: android button audio onclick media-player

我有一个音板,一切正常但是当我在一段时间后点击按钮时声音刚停止播放..这就是代码:

    public class MainActivity extends AppCompatActivity{


        //Sounds/Remixes MediaPlayer
        MediaPlayer sound1, sound2, sound3, sound4, remix1, remix2, remix3, remix4;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


            //Sound MediaPlayers
            sound1= MediaPlayer.create(this, R.raw.sound1);
            sound2= MediaPlayer.create(this, R.raw.sound2);
            sound3= MediaPlayer.create(this, R.raw.sound3);
            sound4= MediaPlayer.create(this, R.raw.sound4);



            //Remixes MediaPlayer
            remix1= MediaPlayer.create(this, R.raw.remix1);
            remix2= MediaPlayer.create(this, R.raw.remix2);
            remix3= MediaPlayer.create(this, R.raw.remix3);
            remix4= MediaPlayer.create(this, R.raw.remix4);




        }

    //Songs stop playing when closing/switching the App
        @Override
        protected void onPause() {
            remix1.pause();
            remix2.pause();
            remix3.pause();
            remix4.pause();
            super.onPause();
        }


    //Remix onClick's
    public void remix1(View view){
        if(remix1.isPlaying() == true){
            remix1.pause();
        }else{
            remix1.start();
        }
    }
    public void remix2(View view){
        if(remix2.isPlaying() == true){
            remix2.pause();
        }else{
            remix2.start();
        }
    }
    public void remix3(View view){
        if(remix3.isPlaying() == true){
            remix3.pause();
        }else{
            remix3.start();
        }
    }
    public void remix4(View view){
        if(remix4.isPlaying() == true){
            remix4.pause();
        }else{
            remix4.start();
        }
    }




    //sound onClick's 
    public void sound1(View view){
        sound1.start();
    }
    public void sound2(View view){
        sound2.start();
    }
    public void sound3(View view){
        sound3.start();
    }
    public void sound4(View view){
        sound4.start();
    }

}

这是我的代码,只有4个声音和4个混音。

声音长达3秒,混音3分钟。

这是我的应用,你可以尝试一下,但有时按钮会停止工作:https://play.google.com/store/apps/details?id=com.aaron.waller.angelasoundboard

我发现的唯一解决方案是每次使用后清理MediaPlayer,我该怎么做?

1 个答案:

答案 0 :(得分:3)

要在每次使用后清理媒体播放器,您应致电

mediaPlayer.release();

但如果您需要的只是在create方法

之后立即将mediaPlayer返回其状态
mediaPlayer.reset();

应该足够了

UPD

在您的情况下,为您使用的每个mediaPlayer将此代码添加到onCreate

mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
    public void onCompletion(MediaPlayer mp) {
        mp.reset();
        //if reset doesnt give you what you need use mp.release() instead
        //but dont forget to call MediaPlayer.create  
        //before next mediaPlayer.start() method

    }
});