Search code examples
javaaudiovolume

Control Clip Volume in Java -> FloatControl Volume does nothing


I am trying to adjust the volume on my game music and I tried the FloatControl volume = … but no matter what value I set it to (1.0f or 0.0f) it is same volume. Any ideas?

public static void playGameSound()
    {
        try {
            AudioInputStream gameSound = AudioSystem.getAudioInputStream(new File("src/res/inGame.wav"));
            play = AudioSystem.getClip();
            play.open(gameSound);
            FloatControl volume = (FloatControl) play.getControl(FloatControl.Type.MASTER_GAIN);
            volume.setValue(1.0f);
            play.loop(Clip.LOOP_CONTINUOUSLY);
        }catch (LineUnavailableException | IOException | UnsupportedAudioFileException e){
            e.printStackTrace();
        }
    }

Solution

  • My experience with the various Control lines for audio is that they are reliant on the sound system of the client computer, and thus there is a lot of variation in what does or doesn't work. For this reason, I use SourceDataLine as my output and control the volume by multiplying every sound frame by a volume factor. You can use a free library I wrote (or inspect its code to write your own) that makes use of this method. The main class is called AudioCue and is modeled closely on Clip.