Start / pause button

1

I'm making an application where there will be several buttons, each one will play a different audio. The reproduction of the audio works me the problem is that if you press the button again it does not stop, instead it plays it again without stopping the first playback, that is if I press 3 times it will sound 3 times the same audio. What I want to do is that by pressing the button again or by pressing a different one the one that is sounding will stop

public class TarjetaOberta extends AppCompatActivity {

Button btM;

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

private void references(){

    btM = (Button) findViewById(R.id.btMarta);

}

public void Marta(View view){

    MediaPlayer ring= MediaPlayer.create(TarjetaOberta.this,R.raw.marta);
    ring.start();

}

This is the code of the button that I have created.

    
asked by Pau Bacardit Agset 14.12.2017 в 23:20
source

2 answers

1

then try the following

public void Marta(View view){

if(ring.isPlaying)//Si al momento de presionar el boton esta sonando lo detenemos
    ring.stop();//detenemos 
}
else//de lo contrario lo reproducimos
{
 ring.start();//volvemos a iniciar
}
    
answered by 15.12.2017 / 16:10
source
1

Then create the MediaPlayer instance as global and before playing the sound you place a stop so the sound instance will stop before starting the new

public class TarjetaOberta extends AppCompatActivity {

Button btM;
 MediaPlayer ring;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tarjeta_oberta);
    references();

  ring= MediaPlayer.create(TarjetaOberta.this,R.raw.marta);// al colocarlo en el onCreate solo es necesario referenciarlo 1 vez
}

private void references(){

    btM = (Button) findViewById(R.id.btMarta);

}

public void Marta(View view){

    ring.stop();//detenemos 

    ring.start();//volvemos a iniciar

}

I hope you find it helpful, greetings

    
answered by 15.12.2017 в 06:42