Android媒体播放器正在播放

时间:2018-11-23 04:06:49

标签: android audio android-mediaplayer

我有一个循环播放单一主要音乐theme的游戏。在android上,如果用户按下主屏幕按钮,音乐将根据需要暂停,但是如果用户随后重新打开该应用,则该应用将重置,但音乐主题的两个实例现在会彼此播放并且不同步(就像原始实例仍在后台播放,但无提示)。如何防止主题轨道重复出现?

编辑:好吧,问题是onSurfaceChanged正在创建我的游戏环境的新实例,当然也创建了主题音乐的新实例。

这是我的音频课:

public class Audio extends Token {
private MediaPlayer theme;
private SoundPool sound;
private int[] note = new int[17];
private int i = -1;
boolean toggle = false;
private int death, gliss, themeLoop;
//private float t;
boolean mute = false;
public Audio(Relic relic) {
    theme = MediaPlayer.create(relic.context(), R.raw.theme_start);
    theme.setLooping(true);

    sound = new SoundPool.Builder().setMaxStreams(6).build();

    note[0] = sound.load(relic.context(), R.raw.note1, 1);
    note[1] = sound.load(relic.context(), R.raw.note2, 1);
    note[2] = sound.load(relic.context(), R.raw.note3, 1);
    note[3] = sound.load(relic.context(), R.raw.note4, 1);
    note[4] = sound.load(relic.context(), R.raw.note5, 1);
    note[5] = sound.load(relic.context(), R.raw.note6, 1);
    note[6] = sound.load(relic.context(), R.raw.note7, 1);
    note[7] = sound.load(relic.context(), R.raw.note8, 1);
    note[8] = sound.load(relic.context(), R.raw.note9, 1);
    note[9] = sound.load(relic.context(), R.raw.note10, 1);
    note[10] = sound.load(relic.context(), R.raw.note11, 1);
    note[11] = sound.load(relic.context(), R.raw.note12, 1);
    note[12] = sound.load(relic.context(), R.raw.note13, 1);
    note[13] = sound.load(relic.context(), R.raw.note14, 1);
    note[14] = sound.load(relic.context(), R.raw.note15, 1);
    note[15] = sound.load(relic.context(), R.raw.note16, 1);
    note[16] = sound.load(relic.context(), R.raw.note17, 1);

    death = sound.load(relic.context(), R.raw.death, 1);
    gliss = sound.load(relic.context(), R.raw.gliss, 1);

    playTheme();
}
public void playTheme() {
    play(theme);
}
public void playNote() {
    i = (i+1) % 17;
    play(note[i]);
}
public void addPoints(int value) {
    if (value > 1) {
        play(gliss);
    } else {
        playNote();
    }
}
public void gameover() {
    play(death);
}
private void play(int i) {
    if (!mute) {
        sound.play(i, 1, 1, 1, 0, 1);
    }
}
private void play(MediaPlayer player) {
    if(!mute) {
        player.start();
    }
}
private void pause(MediaPlayer player) {
    player.pause();
}
public void mute() {
    mute = true;
    pause(theme);
}
public void unmute() {
    mute = false;
    play(theme);
}
public void pause() {
    // this is called from Activity.onPause
    theme.stop();
    theme.release();
    theme = null;
 }
}

1 个答案:

答案 0 :(得分:1)

您可以做的是尝试完全停止mp3,而不是暂停它。因此,您可以像这样覆盖onPauseonStart方法:

@Override
public void onPause(){
   super.onPause();
   myMP3.stop();
}

@Override
public void onResume(){
   super.onResume();
   myMP3.start();
}

现在,当您的应用暂停(或暂时关闭)时,它将完全停止mp3。当您的应用恢复时,它将再次启动mp3。我希望这会有所帮助!