0

I have different buttons which each of them have sound effect. for set sound effect I used this class:

public class Effects {
    private static final String TAG = Effects.class.toString();

    private static final Effects INSTANCE = new Effects();


    public static final int SOUND_1 = 1;
    public static final int SOUND_2 = 2;

    private Effects() {

    }

    public static Effects getInstance() {
        return INSTANCE;
    }

    private SoundPool soundPool;
    private HashMap<Integer, Integer> soundPoolMap;
    int priority = 1;
    int no_loop = 0;
    private int volume;
    float normal_playback_rate = 1f;

    private Context context;

    public void init(Context context) {
        this.context = context;
        soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
        soundPoolMap = new HashMap<Integer, Integer>();
        soundPoolMap.put(SOUND_1, soundPool.load(context, R.raw.laser, 1));

        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        volume = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
    }

    public void playSound(int soundId) {
        Log.i(TAG, "!!!!!!!!!!!!!! playSound_1 !!!!!!!!!!");
        soundPool.play(soundId, volume, volume, priority, no_loop, normal_playback_rate);

    }
    ...
}

and then in my activity I used this code to identify my class to apply the sound.

Effects.getInstance().init(this);

and in my onclick of my button :

Effects.getInstance().playSound(Effects.SOUND_1);

it works correctly. but now I want another button like disable to disable the sound for all my buttons . when I click on my Button (disable ) I used this code:

 button(my_button_name).setSoundEffectsEnabled(false);

but it doesn't work. what's the problem?

Konrad Krakowiak
  • 12,285
  • 11
  • 58
  • 45
eli
  • 23
  • 6

1 Answers1

0

Add to you your Effects class boolean variable mSoundEffectsEnabled and method

public void setSoundEffectsEnabled(boolean enabled){
    mSoundEffectsEnabled = enabled;
}

And change your methods like this:

public void init(Context context) {
    this.context = context;
    soundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 100);
    soundPoolMap = new HashMap<Integer, Integer>();
    soundPoolMap.put(SOUND_1, soundPool.load(context, R.raw.laser, 1));

    AudioManager audioManager = (AudioManager)     context.getSystemService(Context.AUDIO_SERVICE);
    volume = audioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
    setSoundEffectsEnabled(true);
 }

public void playSound(int soundId) {
    if (mSoundEffectsEnabled){
        Log.i(TAG, "!!!!!!!!!!!!!! playSound_1 !!!!!!!!!!");
        soundPool.play(soundId, volume, volume, priority, no_loop,     normal_playback_rate);
    }
}

Now you can disable or enable sound effects in any time by calling Effects.getInstance().setSoundEffectsEnabled(flag)

Denys Vasylenko
  • 2,135
  • 18
  • 20