Java中的音量控制(增加或减少)

时间:2009-06-04 23:20:27

标签: java audio javasound

如何使用Java增加传出wav音频流的音量?我遇到了各种Java TTS引擎和合成语音输出量的问题。是否有API调用或doo-hickey.jar我可以用来提高音量?

3 个答案:

答案 0 :(得分:34)

如果您使用的是Java Sound API,则可以使用MASTER_GAIN控件设置音量。

import javax.sound.sampled.*;

AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(
    new File("some_file.wav"));
Clip clip = AudioSystem.getClip();
clip.open(audioInputStream);
FloatControl gainControl = 
    (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
gainControl.setValue(-10.0f); // Reduce volume by 10 decibels.
clip.start();

答案 1 :(得分:10)

您可以使用GainControl调整音量,打开行

后尝试这样的操作
FloatControl volume= (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN); 

答案 2 :(得分:1)

public final class VolumeControl
{

    private VolumeControl(){}

    private static LinkedList<Line> speakers = new LinkedList<Line>();

    private final static void findSpeakers()
    {
        Mixer.Info[] mixers = AudioSystem.getMixerInfo();

        for (Mixer.Info mixerInfo : mixers)
        {
            if(!mixerInfo.getName().equals("Java Sound Audio Engine")) continue;

            Mixer mixer         = AudioSystem.getMixer(mixerInfo);
            Line.Info[] lines   = mixer.getSourceLineInfo();

            for (Line.Info info : lines)
            {

                try 
                {
                    Line line = mixer.getLine(info);
                    speakers.add(line);

                }
                catch (LineUnavailableException e)      { e.printStackTrace();                                                                                  } 
                catch (IllegalArgumentException iaEx)   {                                                                                                       }
            }
        }
    }

    static
    {
        findSpeakers();
    }

    public static void setVolume(float level)
    {
        System.out.println("setting volume to "+level);
        for(Line line : speakers)
        {
            try
            {
                line.open();
                FloatControl control = (FloatControl)line.getControl(FloatControl.Type.MASTER_GAIN);
                control.setValue(limit(control,level));
            }
            catch (LineUnavailableException e) { continue; }
            catch(java.lang.IllegalArgumentException e) { continue; }



        }
    }

    private static float limit(FloatControl control,float level)
    { return Math.min(control.getMaximum(), Math.max(control.getMinimum(), level)); }

}