play and stop sound by different button click in same time Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of play and stop sound by different button click in same time without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I tried with the following code. My app is a kids’ learning app and there I set many sounds. While one button is clicked it’s playing, but in the same time, another button click is not working before end of the first sound. I want to release the first sound while another button will click at the 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();
}

Can you please edit and explain how I will solve the problem? Thanks.

Answer

I would suggest stopping the player each time a button is clicked. You may consider the following implementation.

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();
}
We are here to answer your question about play and stop sound by different button click in same time - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji