Search code examples
javaandroidandroid-mediaplayersoundpoolmute

How to mute a soundpool?


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

}

Solution

  • 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
        }
    }