所以我正在为Android制作声音应用程序而且我遇到了一个小问题。
当我点击button1时,它会播放声音。这部分工作正常,但我希望我的应用程序在点击button2时停止当前的媒体播放器,并播放按钮2声音。
final MediaPlayer mp = MediaPlayer.create(this, R.raw.kalas);
ImageButton sound1=(ImageButton) findViewById(R.id.sound1);
sound1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp.isPlaying()) {
mp.pause();
mp.seekTo(0);
}
else {
mp.start();
}
}
});
答案 0 :(得分:2)
ImageButton sound2=(ImageButton) findViewById(R.id.sound2);
sound2.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
// TODO Auto-generated method stub
if (mp.isPlaying()) {
mp.pause();
mp.seekTo(0);
}
mp.start();
}
});
答案 1 :(得分:1)
这是完整代码的解决方案:)
final MediaPlayer mp = MediaPlayer.create(this, R.raw.kalas);
ImageButton sound1=(ImageButton) findViewById(R.id.sound1);
sound1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp.isPlaying()) {
mp.pause();
mp.seekTo(0);
}
else {
mp.start();
}
}
});
ImageButton sound2=(ImageButton) findViewById(R.id.sound2);
sound2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mp.isPlaying()) {
mp.pause();
mp.seekTo(0);
}
else {
mp.start();
}
}
});
答案 2 :(得分:0)
创建新的ImageButton并将onClickListener
设置为该按钮并检查它是否正在播放,然后按mp.stop();
final MediaPlayer mp = MediaPlayer.create(this, R.raw.kalas);
ImageButton sound1=(ImageButton) findViewById(R.id.sound1);
ImageButton sound2=(ImageButton) findViewById(R.id.sound2);
sound1.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
// TODO Auto-generated method stub
if (mp.isPlaying()) {
mp.pause();
mp.seekTo(0);
}
else {
mp.start();
}
}
});
sound2.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
// TODO Auto-generated method stub
if (mp.isPlaying()) {
mp.stop
}
}
});
答案 3 :(得分:0)
先打电话播放歌曲时。试试这可能对你有帮助
public MediaPlayer StopMediaPlayer(MediaPlayer mediaPlayer) {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
return mediaPlayer;
}