Saturday, May 31, 2025

[JAVA] VOLUME AUDIO

import javax.sound.sampled.*;

public class VolumeControl {
    public static void main(String[] args) {
        try {
            // Load an audio file
            AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(VolumeControl.class.getResource("audio.wav"));
            // Get a clip
            Clip clip = AudioSystem.getClip();
            // Open the clip
            clip.open(audioInputStream);
            // Get the master gain control
            FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);

            // Set the volume (example: 50% of the maximum)
            float maxGain = gainControl.getMaximum();
            float minGain = gainControl.getMinimum();
            float range = maxGain - minGain;
            float volume = minGain + (range * 0.5f); // 50%
            gainControl.setValue(volume);

            // Start playing
            clip.start();

            // Keep the program running while the audio plays
            Thread.sleep(clip.getMicrosecondLength() / 1000);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

No comments: