How to create a mute option

Tyilo picture Tyilo · Aug 8, 2011 · Viewed 8.3k times · Source

How do I create a function that toggles mute for the whole java application?

Actually all the sound comes from an external applet I load in the application.

The code for loading the applet is here: https://github.com/Tyilo/RS2Lite/blob/master/src/com/rs2lite/loader/GameAppletLoader.java

Answer

Florian picture Florian · Aug 9, 2011

There is the Port which gives you access to the computer's mixer, but muting sound there would mute all sound of the computer. So that's probably not a good option.

Other than that, I believe that you require the class instance of the Clip or SourceDataLine that currently plays. Most probably, however, the applet uses Applet's AudioClip class for playback, which may or may not use a Clip/SourceDataLine internally...

Anyway, you can try the following approach, it should work on most Java Sound implementations:

  • from AudioSystem, get all mixers

    Mixer.Info[] infos = AudioSystem.getMixerInfo();
    for (Mixer.Info info: infos) {
        Mixer mixer = AudioSystem.getMixer(info);
    }
    

    make sure to import javax.sound.sampled.*

  • from each Mixer, retrieve the playback lines with getSourceLines()
  • for each returned line, try to get the Mute control:

    BooleanControl bc = (BooleanControl) line.getControl(BooleanControl.Type.MUTE)
    if (bc != null) {
        bc.setValue(true); // true to mute the line, false to unmute
    }
    

Note that there is no guarantee that you will get lines, and no guarantee that the Java Sound implementation provides the MUTE control for a given line.