通过同时单击不同按钮播放和停止声音

play and stop sound by different button click in same time

我尝试了以下代码。我的应用程序是一个儿童学习应用程序,我在那里设置了很多声音。单击一个按钮时它正在播放,但与此同时,在第一个声音结束之前单击另一个按钮不起作用。我想在释放第一个声音的同时按下另一个按钮。

public void soreo (View v){
    Button button = (Button)findViewById(R.id.Soreo);
    final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.bounce);
    button.startAnimation(myAnim);
    if (player == null){
        player = MediaPlayer.create(this, R.raw.soreo);
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopPlayer();
            }
        });
    }
    player.start();
}

public void sorea (View v){
    Button button = (Button)findViewById(R.id.Sorea);
    final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.bounce);
    button.startAnimation(myAnim);
    if (player == null){
        player = MediaPlayer.create(this, R.raw.sorea);
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopPlayer();
            }
        });
    }
    player.start();
}

public void stopPlayer (){
    if (player!=null){
        player.stop();
        player.reset();
        player.release();
        player=null;
    }
}

@Override
protected void onStop (){
    super.onStop();
    stopPlayer();
}

你能编辑并解释一下我将如何解决这个问题吗?谢谢

我建议每次单击按钮时停止播放器。您可以考虑以下实现。

public void sorea (View v){
    Button button = (Button) findViewById(R.id.Sorea);
    final Animation myAnim = AnimationUtils.loadAnimation(this, R.anim.bounce);

    stopPlayer(); // Call StopPlayer here 

    button.startAnimation(myAnim);
    if (player == null){
        player = MediaPlayer.create(this, R.raw.sorea);
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                stopPlayer();
            }
        });
    }
    player.start();
}