【问题标题】:play and stop sound by different button click in same time通过同时点击不同的按钮来播放和停止声音
【发布时间】:2020-01-27 12:35:19
【问题描述】:

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

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();
}

您能否编辑并解释我将如何解决该问题?谢谢。

【问题讨论】:

    标签: java android android-mediaplayer media-player onclicklistener


    【解决方案1】:

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

    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();
    }
    

    【讨论】:

    • 很高兴知道我能帮上忙!祝您的孟加拉语学习应用程序好运!
    猜你喜欢
    • 1970-01-01
    • 2014-05-20
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多