How do I increase the volume of an outgoing wav audio stream using Java? I'm having issues with various Java TTS engines and the output volume of the synthesized speech. Is there an API call or a doo-hickey.jar I can use to pump up the volume?
Asked
Active
Viewed 8.8k times
3 Answers
43
If you're using the Java Sound API, you can set the volume with the MASTER_GAIN control.
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();

markusk
- 6,477
- 34
- 39
-
Thanx! I'll try this. For what it's worth I'm looking at the problem on both ends. I have an iPhone client ingesting the audio stream and just by using a different API on the client I get different volume. So I don't think my problem is entirely server side. – Cliff Jun 05 '09 at 13:48
-
5@ markusk If the question is specific to volume , `FloatControl.Type.VOLUME` should be used ? – program-o-steve Aug 02 '11 at 17:39
-
4Just for the record: the volume control threw an exception (not supported) while the master gain control didn't (on a `SourceDataLine`). – RedGreasel May 27 '13 at 01:08
11
You can adjust volume using a GainControl, try something like this after you have opened the line
FloatControl volume= (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);

Buhake Sindi
- 87,898
- 29
- 167
- 228

objects
- 8,637
- 4
- 30
- 38
3
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)); }
}

navid
- 566
- 6
- 15

Jan Cajthaml
- 403
- 3
- 13
-
1Adjusting volume on speakers and on one specific track are two entirely different things. – Vojtěch Kaiser Oct 03 '15 at 18:57