我需要一个按钮,按下时会启动,再次按下时会停止。否则我有重叠的声音。你们有人可以帮我解决这个问题吗?下面是我目前所拥有的,当再次点击时无法停止按钮,所以当前正在播放并在声音完成时停止,导致声音重叠。在按下另一个按钮时让一个人停下来也是理想的,但我不知道如何轻松地将其合并。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boardone);
Button one = (Button) findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(BoardoneActivity.this, R.raw.mouse_laughter);
mp.start();
}
});
Button two = (Button) findViewById(R.id.button2);
two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaPlayer mp = MediaPlayer.create(BoardoneActivity.this, R.raw.evil_laugh);
mp.start();
}
});
答案 0 :(得分:3)
不要使用Media Player的两个对象。以下是我项目中的方法片段。如果有任何错误让我知道。
private MediaPlayerManager mRecordingPlayer = null;
private void initAudioPlayer(){
if(mRecordingPlayer == null){
mRecordingPlayer = new MediaPlayerManager();
}
}
private void playMusic(int position){
initAudioPlayer();
mRecordingPlayer.resetPlayer();
mRecordingPlayer.setupPlayback("your reasource");
mRecordingPlayer.startPlaying();
}
private void stopPlaying(){
initAudioPlayer();
if(mRecordingPlayer.isPlaying()){
mRecordingPlayer.pausePlaying();
}
}
@Override
public void onPause() {
clearAudioPlayer();
super.onPause();
}
private void clearAudioPlayer(){
if(mRecordingPlayer != null ){
mRecordingPlayer.resetPlayer();
}
}
@Override
public void onClick(View view) {
boolean on = ((ToggleButton) view).isChecked();
if(on){
playMusic("play music");
((ToggleButton) view).setChecked(true);
}else{
stopPlaying();
}
}
答案 1 :(得分:0)
使用以下代码尝试。
mPlayPause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
if (mp.isPlaying()) {
if (mp != null) {
mp.pause();
mPlayPause.setText("Play");
}
} else {
if (mp != null) {
mp.start();
mPlayPause.setText("Pause");
}
}
}
});