简体   繁体   中英

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

}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM