简体   繁体   中英

Set volume of a Java Clip method not working

Im trying to set the volume of a Clip in Java and Im fairly new to audio programming

Im following a previous post Set volume of Java Clip andswer by Steve but am having trouble using the method.

This is my working code just testing to play an audio file

try {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("C:\\Windows\\Media\\alarm01.wav").getAbsoluteFile());
        Clip clip = AudioSystem.getClip();
        //clip.setVolume(1.0f);
        clip.open(audioInputStream);
        clip.start();
    } catch(Exception ex) {
        System.out.println("Error with playing sound.");
        ex.printStackTrace();
    }

where the commented out line is the one that is producing the error. Below is my entire code in this class

public class Sound {

    /**
     * @param args the command line arguments
     */
    
    private static Clip clip;

    public float getVolume() {
        FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
        return (float) Math.pow(10f, gainControl.getValue() / 20f);
    }

    public static void setVolume(float volume) {
        if (volume < 0f || volume > 1f) {
            throw new IllegalArgumentException("Volume not valid: " + volume);
        }
        FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
        gainControl.setValue(20f * (float) Math.log10(volume));
    }
    
    public static void main(String[] args) throws Exception {
        int vol;
        Toolkit.getDefaultToolkit().beep();
        try {
            vol = Integer.parseInt(args[0]);
        }
        catch (NumberFormatException e) {
            vol = 0;
        }
        try {
        AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(new File("C:\\Windows\\Media\\alarm01.wav").getAbsoluteFile());
        Clip clip = AudioSystem.getClip();
        //clip.setVolume(1.0f);
        clip.open(audioInputStream);
        clip.start();
    } catch(Exception ex) {
        System.out.println("Error with playing sound.");
        ex.printStackTrace();
    }

The reason for the int vol in main is because that is whats meant to actual be the parameter to set the volume once I can get that method working

When I try to do the line

clip.setVolume(int);

it says it cannot find the symbol for the method setVolume and im not sure why

The clip.setVolume() in your code is looking for a setVolume method on the class Clip .

The getVolume() that you created applies to the class Sound .

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