[英]i want to use one same button to play and pause.First click I want to play it & second click I want to pause it
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.