How to mute a soundpool?

怎甘沉沦 提交于 2019-12-13 02:27:07

问题


I want to allow the user to mute the app with a button and someone advised me to ''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.''but i dont know how to do that. Could someone post an example code pls. The pool code :

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();
    }

}

回答1:


Add a variable to your MediaPlayerPool class, let's call it mute

public boolean mute = false;

Have a mute/unmute button and on its onClick method (will toggle):

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

and your playSound method becomes

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


来源:https://stackoverflow.com/questions/48985463/how-to-mute-a-soundpool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!