如何使音池静音?

How to mute a soundpool?

我想允许用户使用按钮将应用静音,有人建议我“'stick a boolean on your MediaPlayerPool that you set to false when the mute button is pressed. Then in your playSound method, do nothing if the value is false.'”,但我不知道该怎么做。有人可以 post 示例代码吗? 池代码:

public class MediaPlayerPool {

    private static MediaPlayerPool instance = null;
    private Context context;
    private List<MediaPlayer> pool;

    public static MediaPlayerPool getInstance(Context context) {
        if(instance == null) {
            instance = new MediaPlayerPool(context);
        }
        return instance;
    }

    private MediaPlayerPool(Context context) {
        this.context = context;
        pool = new ArrayList<>();
    }

    public void playSound(int soundId) {
        MediaPlayer mediaPlayer = MediaPlayer.create(context, soundId);

        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.release();

                pool.remove(mediaPlayer);
                mediaPlayer = null;

            }
        });

        pool.add(mediaPlayer);
        mediaPlayer.start();
    }

}

为您的 MediaPlayerPool 添加一个变量 class,我们称它为 mute

public boolean mute = false;

有一个 mute/unmute 按钮及其 onClick 方法(将切换):

MediaPlayerPool.getInstance().mute = !MediaPlayerPool.getInstance().mute

并且您的 playSound 方法变为

public void playSound(int soundId) {
    if(!mute) {
        // stick your current code here
    }
}