javax.sound.sampled.FloatControl Java Examples

The following examples show how to use javax.sound.sampled.FloatControl. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MultiClip.java    From opsu with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Plays the clip with the specified volume.
 * @param volume the volume the play at
 * @param listener the line listener
 * @throws LineUnavailableException if a clip object is not available or
 *         if the line cannot be opened due to resource restrictions
 */
public void start(float volume, LineListener listener) throws LineUnavailableException {
	Clip clip = getClip();
	if (clip == null)
		return;

	// PulseAudio does not support Master Gain
	if (clip.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
		// set volume
		FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
		float dB = (float) (Math.log(volume) / Math.log(10.0) * 20.0);
		gainControl.setValue(Utils.clamp(dB, gainControl.getMinimum(), gainControl.getMaximum()));
	} else if (clip.isControlSupported(FloatControl.Type.VOLUME)) {
		// The docs don't mention what unit "volume" is supposed to be,
		// but for PulseAudio it seems to be amplitude
		FloatControl volumeControl = (FloatControl) clip.getControl(FloatControl.Type.VOLUME);
		float amplitude = (float) Math.sqrt(volume) * volumeControl.getMaximum();
		volumeControl.setValue(Utils.clamp(amplitude, volumeControl.getMinimum(), volumeControl.getMaximum()));
	}

	if (listener != null)
		clip.addLineListener(listener);
	clip.setFramePosition(0);
	clip.start();
}
 
Example #2
Source File: AudioPlayer.java    From Java-Text-To-Speech-Tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * Sets Gain value. Line should be opened before calling this method. Linear scale 0.0 <--> 1.0 Threshold Coef. : 1/2 to avoid saturation.
 * 
 * @param fGain
 */
public void setGain(float fGain) {
	
	// if (line != null)
	// System.out.println(((FloatControl)
	// line.getControl(FloatControl.Type.MASTER_GAIN)).getValue())
	
	// Set the value
	gain = fGain;
	
	// Better type
	if (line != null && line.isControlSupported(FloatControl.Type.MASTER_GAIN))
		( (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN) ).setValue((float) ( 20 * Math.log10(fGain <= 0.0 ? 0.0000 : fGain) ));
	// OR (Math.log(fGain == 0.0 ? 0.0000 : fGain) / Math.log(10.0))
	
	// if (line != null)
	// System.out.println(((FloatControl)
	// line.getControl(FloatControl.Type.MASTER_GAIN)).getValue())
}
 
Example #3
Source File: SoundTools.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public static FloatControl getControl(AudioInputStream in) {
    try {

        AudioFormat baseFormat = in.getFormat();
        AudioFormat decodedFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
                baseFormat.getSampleRate(),
                16,
                baseFormat.getChannels(),
                baseFormat.getChannels() * 2,
                baseFormat.getSampleRate(),
                false);
        AudioInputStream ain = AudioSystem.getAudioInputStream(decodedFormat, in);
        DataLine.Info info = new DataLine.Info(Clip.class, decodedFormat);
        try ( Clip clip = (Clip) AudioSystem.getLine(info)) {
            clip.open(ain);
            FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
            return gainControl;
        }
    } catch (Exception e) {
        logger.debug(e.toString());
        return null;
    }
}
 
Example #4
Source File: JavaSoundAudioSink.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void setVolume(final PercentType volume) throws IOException {
    if (volume.intValue() < 0 || volume.intValue() > 100) {
        throw new IllegalArgumentException("Volume value must be in the range [0,100]!");
    }
    if (!isMac) {
        runVolumeCommand(new Closure() {
            @Override
            public void execute(Object input) {
                FloatControl volumeControl = (FloatControl) input;
                volumeControl.setValue(volume.floatValue() / 100f);
            }
        });
    } else {
        Runtime.getRuntime()
                .exec(new String[] { "osascript", "-e", "set volume output volume " + volume.intValue() });
        macVolumeValue = volume;
    }
}
 
Example #5
Source File: SoundTools.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public void setGain(float ctrl) {
    try {
        Mixer.Info[] infos = AudioSystem.getMixerInfo();
        for (Mixer.Info info : infos) {
            Mixer mixer = AudioSystem.getMixer(info);
            if (mixer.isLineSupported(Port.Info.SPEAKER)) {
                try ( Port port = (Port) mixer.getLine(Port.Info.SPEAKER)) {
                    port.open();
                    if (port.isControlSupported(FloatControl.Type.VOLUME)) {
                        FloatControl volume = (FloatControl) port.getControl(FloatControl.Type.VOLUME);
                        volume.setValue(ctrl);
                    }
                }
            }
        }
    } catch (Exception e) {

    }
}
 
Example #6
Source File: FxmlControl.java    From MyBox with Apache License 2.0 6 votes vote down vote up
public static void playClip(final File file) {
    Task miaoTask = new Task<Void>() {
        @Override
        protected Void call() {
            try {
                FloatControl control = SoundTools.getControl(file);
                Clip player = SoundTools.playback(file, control.getMaximum() * 0.6f);
                player.start();
            } catch (Exception e) {
            }
            return null;
        }
    };
    Thread thread = new Thread(miaoTask);
    thread.setDaemon(true);
    thread.start();
}
 
Example #7
Source File: AudioPlayer.java    From Java-Speech-Recognizer-Tutorial--Calculator with Apache License 2.0 6 votes vote down vote up
/**
 * Sets Gain value. Line should be opened before calling this method. Linear
 * scale 0.0 <--> 1.0 Threshold Coef. : 1/2 to avoid saturation.
 * 
 * @param fGain
 */
public void setGain(float fGain) {

	// if (line != null)
	// System.out.println(((FloatControl)
	// line.getControl(FloatControl.Type.MASTER_GAIN)).getValue())

	// Set the value
	gain = fGain;

	// Better type
	if (line != null && line.isControlSupported(FloatControl.Type.MASTER_GAIN))
		((FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN))
				.setValue((float) (20 * Math.log10(fGain <= 0.0 ? 0.0000 : fGain)));
	// OR (Math.log(fGain == 0.0 ? 0.0000 : fGain) / Math.log(10.0))

	// if (line != null)
	// System.out.println(((FloatControl)
	// line.getControl(FloatControl.Type.MASTER_GAIN)).getValue())
}
 
Example #8
Source File: AudioPlayer.java    From Java-Speech-Recognizer-Tutorial--Calculator with Apache License 2.0 6 votes vote down vote up
/**
 * Sets Gain value. Line should be opened before calling this method. Linear
 * scale 0.0 <--> 1.0 Threshold Coef. : 1/2 to avoid saturation.
 * 
 * @param fGain
 */
public void setGain(float fGain) {

	// if (line != null)
	// System.out.println(((FloatControl)
	// line.getControl(FloatControl.Type.MASTER_GAIN)).getValue())

	// Set the value
	gain = fGain;

	// Better type
	if (line != null && line.isControlSupported(FloatControl.Type.MASTER_GAIN))
		((FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN))
				.setValue((float) (20 * Math.log10(fGain <= 0.0 ? 0.0000 : fGain)));
	// OR (Math.log(fGain == 0.0 ? 0.0000 : fGain) / Math.log(10.0))

	// if (line != null)
	// System.out.println(((FloatControl)
	// line.getControl(FloatControl.Type.MASTER_GAIN)).getValue())
}
 
Example #9
Source File: MultiClip.java    From opsu-dance with GNU General Public License v3.0 6 votes vote down vote up
/**
* Mute the Clip (because destroying it, won't stop it)
*/
public void mute() {
	try {
		Clip c = getClip();
		if (c == null) {
			return;
		}
		float val = (float) (Math.log(Float.MIN_VALUE) / Math.log(10.0) * 20.0);
		if (val < -80.0f) {
			val = -80.0f;
		}
		((FloatControl) c.getControl(FloatControl.Type.MASTER_GAIN)).setValue(val);
	} catch (IllegalArgumentException ignored) {
	} catch (LineUnavailableException e) {
		e.printStackTrace();
	}
}
 
Example #10
Source File: ClipOpenBug.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    boolean res = true;
    try {
        AudioInputStream ais = new AudioInputStream(
                new ByteArrayInputStream(new byte[2000]),
                new AudioFormat(8000.0f, 8, 1, false, false), 2000); //
        AudioFormat format = ais.getFormat();
        DataLine.Info info = new DataLine.Info(Clip.class, format,
                                               ((int) ais.getFrameLength()
                                                        * format
                                                       .getFrameSize()));
        Clip clip = (Clip) AudioSystem.getLine(info);
        clip.open();
        FloatControl rateControl = (FloatControl) clip.getControl(
                FloatControl.Type.SAMPLE_RATE);
        int c = 0;
        while (c++ < 10) {
            clip.stop();
            clip.setFramePosition(0);
            clip.start();
            for (float frq = 22000; frq < 44100; frq = frq + 100) {
                try {
                    Thread.currentThread().sleep(20);
                } catch (Exception e) {
                    break;
                }
                rateControl.setValue(frq);
            }
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        res = ex.getMessage().indexOf(
                "This method should not have been invoked!") < 0;
    }
    if (res) {
        System.out.println("Test passed");
    } else {
        System.out.println("Test failed");
        throw new Exception("Test failed");
    }
}
 
Example #11
Source File: SoundNotifier.java    From MercuryTrade with MIT License 6 votes vote down vote up
private void play(String wavPath, float db) {
    if (!dnd && db > -40) {
        ClassLoader classLoader = getClass().getClassLoader();
        try (AudioInputStream stream = AudioSystem.getAudioInputStream(classLoader.getResource(wavPath))) {
            Clip clip = AudioSystem.getClip();
            clip.open(stream);
            if (db != 0.0) {
                FloatControl gainControl =
                        (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
                gainControl.setValue(db);
            }
            clip.start();
        } catch (Exception e) {
            logger.error("Cannot start playing wav file: ", e);
        }
    }
}
 
Example #12
Source File: JavaSoundAudioSink.java    From smarthome with Eclipse Public License 2.0 6 votes vote down vote up
private void runVolumeCommand(Closure closure) {
    Mixer.Info[] infos = AudioSystem.getMixerInfo();
    for (Mixer.Info info : infos) {
        Mixer mixer = AudioSystem.getMixer(info);
        if (mixer.isLineSupported(Port.Info.SPEAKER)) {
            Port port;
            try {
                port = (Port) mixer.getLine(Port.Info.SPEAKER);
                port.open();
                if (port.isControlSupported(FloatControl.Type.VOLUME)) {
                    FloatControl volume = (FloatControl) port.getControl(FloatControl.Type.VOLUME);
                    closure.execute(volume);
                }
                port.close();
            } catch (LineUnavailableException e) {
                logger.error("Cannot access master volume control", e);
            }
        }
    }
}
 
Example #13
Source File: DirectAudioDevice.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
private Gain() {

                super(FloatControl.Type.MASTER_GAIN,
                      Toolkit.linearToDB(0.0f),
                      Toolkit.linearToDB(2.0f),
                      Math.abs(Toolkit.linearToDB(1.0f)-Toolkit.linearToDB(0.0f))/128.0f,
                      -1,
                      0.0f,
                      "dB", "Minimum", "", "Maximum");
            }
 
Example #14
Source File: Audio.java    From salty-engine with Apache License 2.0 5 votes vote down vote up
/**
 * Sets the volume of the clip, 1f is the normal volume, 0f is completely quiet and 2f is twice as loud.
 *
 * @param volume the new volume of this audio
 */
public void setVolume(float volume) {

    volume = GeneralUtil.clamp(volume, 0f, 2f);
    final FloatControl gainControl = (FloatControl) getClip().getControl(FloatControl.Type.MASTER_GAIN);
    gainControl.setValue(20f * (float) Math.log10(volume));
    this.volume = volume;
}
 
Example #15
Source File: SoundTools.java    From MyBox with Apache License 2.0 5 votes vote down vote up
public static FloatControl getControl(File file) {
    try {
        try ( AudioInputStream in = AudioSystem.getAudioInputStream(file)) {
            return getControl(in);
        }
    } catch (Exception e) {
        logger.debug(e.toString());
        return null;
    }
}
 
Example #16
Source File: ClipSFXModule.java    From mochadoom with GNU General Public License v3.0 5 votes vote down vote up
public void setPanning(int chan,int sep){
Clip c=channels[chan];

if (c.isControlSupported(Type.PAN)){
	FloatControl bc=(FloatControl) c.getControl(Type.PAN);
	// Q: how does Doom's sep map to stereo panning?
	// A: Apparently it's 0-255 L-R.
	float pan= bc.getMinimum()+(bc.getMaximum()-bc.getMinimum())*(float)sep/ISoundDriver.PANNING_STEPS;
	bc.setValue(pan);
	}
}
 
Example #17
Source File: AudioPlayer.java    From subsonic with GNU General Public License v3.0 5 votes vote down vote up
public AudioPlayer(InputStream in, Listener listener) throws Exception {
    this.in = in;
    this.listener = listener;

    AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, true);
    line = AudioSystem.getSourceDataLine(format);
    line.open(format);
    LOG.debug("Opened line " + line);

    if (line.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
        gainControl = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
        setGain(DEFAULT_GAIN);
    }
    new AudioDataWriter();
}
 
Example #18
Source File: AudioPlayer.java    From airsonic-advanced with GNU General Public License v3.0 5 votes vote down vote up
public AudioPlayer(InputStream in, Listener listener) throws Exception {
    this.in = in;
    this.listener = listener;

    AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, 44100.0F, 16, 2, 4, 44100.0F, true);
    line = AudioSystem.getSourceDataLine(format);
    line.open(format);
    LOG.debug("Opened line " + line);

    if (line.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
        gainControl = (FloatControl) line.getControl(FloatControl.Type.MASTER_GAIN);
        setGain(DEFAULT_GAIN);
    }
    new AudioDataWriter();
}
 
Example #19
Source File: MetronomePlugin.java    From plugins with GNU General Public License v3.0 5 votes vote down vote up
@Subscribe
private void onConfigChanged(ConfigChanged event)
{
	if (!event.getGroup().equals("metronome"))
	{
		return;
	}

	if (event.getKey().equals("volume"))
	{
		float gainValue = (((float) config.volume()) * 40f / 100f) - 35f;
		FloatControl gainControlTick = (FloatControl) tickClip.getControl(FloatControl.Type.MASTER_GAIN);
		gainControlTick.setValue(gainValue);

		FloatControl gainControlTock = (FloatControl) tockClip.getControl(FloatControl.Type.MASTER_GAIN);
		gainControlTock.setValue(gainValue);
	}
	if (event.getKey().equals("tickSoundFilePath"))
	{
		if (tickClip != null)
		{
			tickClip.close();
		}
		tickClip = GetAudioClip(config.tickPath());
	}
	if (event.getKey().equals("tockSoundFilePath"))
	{
		if (tockClip != null)
		{
			tockClip.close();
		}
		tockClip = GetAudioClip(config.tockPath());
	}
}
 
Example #20
Source File: JavaSoundAudioDevice.java    From epic-inventor with GNU General Public License v2.0 5 votes vote down vote up
public void setLineGain(float gain) {
    if (source != null) {
        if (source.isControlSupported(FloatControl.Type.MASTER_GAIN)) {
            FloatControl volControl = (FloatControl) source.getControl(FloatControl.Type.MASTER_GAIN);
            float newGain = Math.min(Math.max(gain, volControl.getMinimum()), volControl.getMaximum());

            volControl.setValue(newGain);
        }
    }
}
 
Example #21
Source File: SoundTools.java    From MyBox with Apache License 2.0 5 votes vote down vote up
public static FloatControl getControl(URL url) {
    try {
        try ( AudioInputStream in = AudioSystem.getAudioInputStream(url)) {
            return getControl(in);
        }
    } catch (Exception e) {
        logger.debug(e.toString());
        return null;
    }
}
 
Example #22
Source File: Beeper.java    From zxpoly with GNU General Public License v3.0 5 votes vote down vote up
@Override
public float getMasterGain() {
  final FloatControl gainControl = this.gainControl.get();
  if (gainControl == null || !this.working) {
    return -1.0f;
  } else {
    return gainControl.getValue();
  }
}
 
Example #23
Source File: LWaveSound.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
private void rawplay(AudioFormat trgFormat, AudioInputStream ain, float volume)
		throws IOException, LineUnavailableException {
	byte[] data = new byte[8192];
	try {
		clip = getLine(ain, trgFormat);
		if (clip == null) {
			return;
		}
		Control.Type vol1 = FloatControl.Type.VOLUME, vol2 = FloatControl.Type.MASTER_GAIN;
		FloatControl c = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);
		float min = c.getMinimum();
		float v = volume * (c.getMaximum() - min) / 100f + min;
		if (this.clip.isControlSupported(vol1)) {
			FloatControl volumeControl = (FloatControl) this.clip.getControl(vol1);
			volumeControl.setValue(v);
		} else if (this.clip.isControlSupported(vol2)) {
			FloatControl gainControl = (FloatControl) this.clip.getControl(vol2);
			gainControl.setValue(v);
		}
		clip.start();
		int nBytesRead = 0;
		while (isRunning && (nBytesRead != -1)) {
			nBytesRead = ain.read(data, 0, data.length);
			if (nBytesRead != -1) {
				clip.write(data, 0, nBytesRead);
			}
		}
	} finally {
		clip.drain();
		clip.stop();
		clip.close();
		ain.close();
	}
}
 
Example #24
Source File: JoggStreamer.java    From RipplePower with Apache License 2.0 5 votes vote down vote up
public void updateVolume(int percent) {
	if (out != null && out.isOpen()) {
		try {
			FloatControl c = (FloatControl) out.getControl(FloatControl.Type.MASTER_GAIN);
			float min = c.getMinimum();
			float v = percent * (c.getMaximum() - min) / 100f + min;
			c.setValue(v);
		} catch (IllegalArgumentException e) {
		}
	}
	volume = percent;
}
 
Example #25
Source File: Beeper.java    From zxpoly with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void setMasterGain(final float valueInDb) {
  final FloatControl gainControl = this.gainControl.get();
  if (gainControl != null && this.working) {
    gainControl.setValue(
        Math.max(gainControl.getMinimum(), Math.min(gainControl.getMaximum(), valueInDb)));
  }
}
 
Example #26
Source File: WaveEngine.java    From nullpomino with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Set the volume
 * @param vol New configuration volume (1.0The default )
 */
public void setVolume(double vol) {
	volume = vol;

	Set<String> set = clipMap.keySet();
	for(String name: set) {
		try {
			Clip clip = clipMap.get(name);
			FloatControl ctrl = (FloatControl)clip.getControl(FloatControl.Type.MASTER_GAIN);
			ctrl.setValue((float)Math.log10(volume) * 20);
		} catch (Exception e) {}
	}
}
 
Example #27
Source File: DefaultSoundEffect.java    From petscii-bbs with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Sets the volume.
 * 
 * @param vol the volume
 */
private void setVolume(final int vol) {
  
  int volume = vol;
  if (volume < 0) {
    
    volume = MAX_VOLUME;
  }
  float gainDb = 0.0f;
  final FloatControl gain = (FloatControl)
      clip.getControl(FloatControl.Type.MASTER_GAIN);
  
  if (volume == 0) {
    
    gainDb = gain.getMinimum();
    
  } else if (volume < MAX_VOLUME) {
    
    // The volume algorithm is subtractive: The implementation assumes that
    // the sound is already at maximum volume, so we avoid distortion by
    // making the amplitude values
    // The scaling factor for the volume would be 20 normally, but
    // it seems that 13 is better
    gainDb = (float) (Math.log10(MAX_VOLUME - volume) * 13.0);
  }    
  gain.setValue(-gainDb);
}
 
Example #28
Source File: OggClip.java    From desktopclient-java with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Attempt to set the global gain (volume ish) for the play back. If the
 * control is not supported this method has no effect. 1.0 will set maximum
 * gain, 0.0 minimum gain
 *
 * @param gain The gain value
 */
private void setGain(float gain) {
    if (gain != -1) {
        if ((gain < 0) || (gain > 1)) {
            throw new IllegalArgumentException("Volume must be between 0.0 and 1.0");
        }
    }

    this.gain = gain;

    if (outputLine == null) {
        return;
    }

    try {
        FloatControl control = (FloatControl) outputLine.getControl(FloatControl.Type.MASTER_GAIN);
        if (gain == -1) {
            control.setValue(0);
        } else {
            float max = control.getMaximum();
            float min = control.getMinimum(); // negative values all seem to be zero?
            float range = max - min;

            control.setValue(min + (range * gain));
        }
    } catch (IllegalArgumentException e) {
        // gain not supported
        e.printStackTrace();
    }
}
 
Example #29
Source File: JavaMixer.java    From Spark with Apache License 2.0 5 votes vote down vote up
public ControlNode(Control control) {
    super(control.getType(), true);
    this.control = control;
    if (control instanceof BooleanControl) {
        component = createControlComponent((BooleanControl) control);
    } else if (control instanceof EnumControl) {
        component = createControlComponent((EnumControl) control);
    } else if (control instanceof FloatControl) {
        component = createControlComponent((FloatControl) control);
    } else {
        component = null;
    }
}
 
Example #30
Source File: SoftMixingDataLine.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
private Gain() {

            super(FloatControl.Type.MASTER_GAIN, -80f, 6.0206f, 80f / 128.0f,
                    -1, 0.0f, "dB", "Minimum", "", "Maximum");
        }