I have a button called ” micro” , when I click on my sound is played , and when I click on again it must stop
I tried the code below but when I click on my button for the second time , the music is played again and again without stopping:
Button micro=(Button)findViewById(R.id.micro);
micro.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(),
R.raw.mymusic);
mp.start();
}
if(event.getAction() == MotionEvent.ACTION_UP){
MediaPlayer mp = MediaPlayer.create(getBaseContext(),
R.raw.mymusic);
mp.stop();
}
return true;
}
});
You are creating separate
MediaPlayerobjects. You should just create one that you tell to start and stop as necessary.Right now you’re telling one to start, and then later telling a different one to stop.