And when I click it again I want to play it. Here is my code but it's not working as when i click the button again and again is starts repeating the same audio again and again instead of pausing is. Please help me
Button button_attention = (Button)findViewById(R.id.button_one);
button_attention.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
player=MediaPlayer.create(MainActivity.this, R.raw.alarm_effect);
{
if (player.isPlaying()){
player.stop();}
else {
player.start();
}
}
You are re-defining the media player inside of the on-click handler each time that it is called, therefore it will not work. You need to move the definition outside of the on-click handler and then reference it from within.
//Move it to here
player=MediaPlayer.create(MainActivity.this, R.raw.alarm_effect);
Button button_attention = (Button)findViewById(R.id.button_one);
button_attention.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (player.isPlaying()){
//This maybe should be pause.
player.stop();
}
else {
player.start();
}
EDIT: Further to your comment regarding how to use this for multiple tracks, you should do something like the following.
Implement a method, such as the following:
private void changeTrack(int resourceId){
player = MediaPlayer.create(MainActivity.this, resourceId);
}
Simply call this method when you wish to change the track using:
changeTrack(R.raw.MEDIA_NAME);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.