Setting the Volume of a Sampled Audio Player - Java Media

Java examples for Media:Audio

Description

Setting the Volume of a Sampled Audio Player

Demo Code


import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;

import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.BooleanControl;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.FloatControl;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;

public class Main {
  public static void main(String[] argv) {
    try {//from  ww  w.j  av  a2s  .  c  o m
      AudioInputStream stream = AudioSystem.getAudioInputStream(new File(
          "audiofile"));

      AudioFormat format = stream.getFormat();
      if (format.getEncoding() != AudioFormat.Encoding.PCM_SIGNED) {
        format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED,
            format.getSampleRate(), format.getSampleSizeInBits() * 2,
            format.getChannels(), format.getFrameSize() * 2,
            format.getFrameRate(), true); // big endian
        stream = AudioSystem.getAudioInputStream(format, stream);
      }

      DataLine.Info info = new DataLine.Info(Clip.class, stream.getFormat(),
          ((int) stream.getFrameLength() * format.getFrameSize()));
      Clip clip = (Clip) AudioSystem.getLine(info);

      // This method does not return until the audio file is completely loaded
      clip.open(stream);
      // Set Volume
      FloatControl gainControl = (FloatControl) clip
          .getControl(FloatControl.Type.MASTER_GAIN);
      double gain = .5D; // number between 0 and 1 (loudest)
      float dB = (float) (Math.log(gain) / Math.log(10.0) * 20.0);
      gainControl.setValue(dB);

      // Mute On
      BooleanControl muteControl = (BooleanControl) clip
          .getControl(BooleanControl.Type.MUTE);
      muteControl.setValue(true);

      // Mute Off
      muteControl.setValue(false);// Start playing
      clip.start();
    } catch (Exception e) {
    }
  }

}

Related Tutorials