gpt4 book ai didi

Android - 如何在不停止 TimerTask 的情况下将 SoundPool 静音

转载 作者:行者123 更新时间:2023-11-30 05:05:26 30 4
gpt4 key购买 nike

我正在尝试创建节拍器声音,但是无法正常工作的是将其静音的功能。我希望能够在不停止 TimerTask 的情况下将其静音,因为我希望在取消静音后速率保持一致。这是我的代码:

public class Metronome {
private boolean mute;
private boolean playing = false;
private Timer mainTimer;
private SoundPool mSoundPool;
int mSoundID;

public Metronome(Context context) {
mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
mSoundID = mSoundPool.load(context, R.raw.metronome, 1);
}

public void play(float pace, boolean mute) {
mainTimer = new Timer();
MyTimerTask mainTimerTask = new MyTimerTask();
mainTimer.schedule(mainTimerTask, 0, Math.round(pace * 1000));
this.mute = mute;
playing = true;
}

public void stop() {
mainTimer.cancel();
mainTimer.purge();
playing = false;
}

public boolean isPlaying() {
return playing;
}

public void setMute(boolean mute) {
this.mute = mute;
if (mute) {
mSoundPool.setVolume(mSoundID, 0, 0);
} else {
mSoundPool.setVolume(mSoundID, 1, 1);
}
}

private void playSound() {
if (!mute) {
mSoundPool.play(mSoundID, 1, 1, 1, 0, 1);
}
}

class MyTimerTask extends TimerTask {

@Override
public void run() {
playSound();
}
}
}

但是,调用 setMute(true) 不起作用。有谁知道如何让我的 SoundPool 静音?

最佳答案

想通了。它在我使用静态方法和变量时有效。

public class Metronome {
public static boolean mute = false;
public static boolean playing = false;
private static Timer mainTimer;
private static SoundPool soundPool;
private static int soundID;

public static void loadSound(Context context) {
soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
soundID = soundPool.load(context, R.raw.metronome, 1);
}

public static void play(float pace, boolean isMuted) {
mainTimer = new Timer();
MyTimerTask mainTimerTask = new MyTimerTask();
mainTimer.schedule(mainTimerTask, 0, Math.round(pace * 1000));
mute = isMuted;
playing = true;
}

public static void stop() {
mainTimer.cancel();
mainTimer.purge();
playing = false;
}

static class MyTimerTask extends TimerTask {
@Override
public void run() {
playSound();
}

private void playSound() {
if (!mute) {
soundPool.play(soundID, 1, 1, 1, 0, 1);
}
}
}
}

关于Android - 如何在不停止 TimerTask 的情况下将 SoundPool 静音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54660420/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com