java点击按钮停止音乐,Android按钮点击播放音乐,再次点击停止音乐

I have a button, when I click it plays music, how to do it, when I click second time, to stop the music?

Button two = (Button)this.findViewById(R.id.button2);

final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.two);

two.setOnClickListener(new OnClickListener(){

public void onClick(View v) {

mp2.start();

}

});

Ok, this one works:

Button one = (Button)this.findViewById(R.id.button1);

final MediaPlayer mp1 = MediaPlayer.create(this, R.raw.n);

one.setOnClickListener(new OnClickListener(){

@Override

public void onClick(View v) {

if (mp1.isPlaying()) {

mp2.pause();

}

else {

mp2.start();

}

;

}});

The one with Pause above it works, but If I want to stop the music, it does not work.

Following not working:

@Override

public void onClick(View v) {

if (mp1.isPlaying()) {

mp2.stop();

}

else {

mp2.start();

}

;

}});

I get error: start called in state 0

error (-38, 0)

解决方案Button two = (Button)this.findViewById(R.id.button2);

final MediaPlayer mp2 = MediaPlayer.create(this, R.raw.two);

two.setOnClickListener(new OnClickListener(){

public void onClick(View v) {

// If the music is playing

if(mp2.isPlaying() == true)

// Pause the music player

mp2.pause();

// If it's not playing

else

// Resume the music player

mp2.start();

}

});

You can actually write just

if(mp2.isPlaying())

instead of

if(mp2.isPlaying() == true)

It's just for the sake of understanding what is going on.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值