在我的应用程序中,我制作了一个音乐背景,该音乐背景在单击按钮启动时起作用,并且音乐更改了循环sound1,sound2,sound3。
public void startNewGame() {//initializing the sounds
final MediaPlayer sound1 = MediaPlayer.create(this, R.raw.music1);
final MediaPlayer sound2 = MediaPlayer.create(this, R.raw.music2);
final MediaPlayer sound3 = MediaPlayer.create(this, R.raw.music3);
//generate random number
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(3) + 1;
//picking the right sound to play
switch (randomInt){
case 1:
if ( !sound1.isPlaying())
sound1.setLooping(true);
sound1.start();
break;
case 2: if ( !sound2.isPlaying() )
sound2.setLooping(true);
sound2.start();
break;
case 3:
if ( !sound3.isPlaying() )
sound3.setLooping(true);
sound3.start();
break;
}
mBtnChooseAndStart.setVisibility(View.GONE);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fl_board_container,
GameFragment.newInstance(mBitmapBricks, GOAL_STATUS))
.commit();
}
最重要的是,当我再次单击另一个按钮重新启动时,在确认后会生成对话,但是我启动了游戏,但是有另一个声音起作用了,但第一个声音没有停止 如何解决这个问题,先谢谢
public void restart(View view) {
if (mFullBitmap == null) {
// Not started, so cannot restart
UIUtils.toast(this, getString(R.string.not_started));
return;
}
new AlertDialog.Builder(this)
.setTitle(getString(R.string.restart))
.setMessage(getString(R.string.confirm_restart_msg))
.setPositiveButton(getString(R.string.confirm), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startNewGame();
}
})
.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
,以及如何停止onBackpressed()中的声音。
答案 0 :(得分:0)
最后我找到了解决方案,它可以正常工作 首先创建一种停止媒体播放器的方法
public void cleanUpMediaPlayer(){
if(mediaPlayer != null) {
if(mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
}
然后创建一种为每种声音启动的方法,并且在此方法中,有必要应用functin来停止mediaplayer(如果存在)
public void sound1(){
cleanUpMediaPlayer();
mediaPlayer = MediaPlayer.create(this, R.raw.music1);
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
public void sound2(){
cleanUpMediaPlayer();
mediaPlayer = MediaPlayer.create(this, R.raw.music2);
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
public void sound3(){
cleanUpMediaPlayer();
mediaPlayer = MediaPlayer.create(this, R.raw.music3);
mediaPlayer.setLooping(true);
mediaPlayer.start();
}
最终在所需的时刻发出声音 对我来说,我希望每次玩游戏时都能改变声音,这就是为什么我在切换循环中使用随机的原因。
Random randomGenerator = new Random();
int randomInt = randomGenerator.nextInt(3) + 1;
//picking the right sound to play
switch (randomInt){
case 1:
sound1();
break;
case 2:
sound2();
break;
case 3:
sound3();
break;
}
onBackPressed()相同,只需要调用cleanUpMediaPlayer方法
public void onBackPressed() {
cleanUpMediaPlayer();
... }
对我的朋友mistek来说是美好的一天:)