Setting the Volume of Playing Midi Audio - Java Media

Java examples for Media:Audio

Description

Setting the Volume of Playing Midi Audio

Demo Code

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

import javax.sound.midi.InvalidMidiDataException;
import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Sequence;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Synthesizer;

public class Main {

  public void main(String[] argv) {
    try {/*w w  w.  j  a va2s  .c o m*/
      // From file
      Sequence sequence = MidiSystem.getSequence(new File("midifile"));

      // From URL
      sequence = MidiSystem.getSequence(new URL("http://hostname/midifile"));

      // Create a sequencer for the sequence
      Sequencer sequencer = MidiSystem.getSequencer();
      sequencer.open();
      sequencer.setSequence(sequence);
      // To create a Sequencer object, see Loading and Playing Midi Audio

      if (sequencer instanceof Synthesizer) {
        Synthesizer synthesizer = (Synthesizer) sequencer;
        MidiChannel[] channels = synthesizer.getChannels();

        // gain is a value between 0 and 1 (loudest)
        double gain = 0.9D;
        for (int i = 0; i < channels.length; i++) {
          channels[i].controlChange(7, (int) (gain * 127.0));
        }
      }
      // Start playing
      sequencer.start();
    } catch (MalformedURLException e) {
    } catch (IOException e) {
    } catch (MidiUnavailableException e) {
    } catch (InvalidMidiDataException e) {
    }
  }
}

Related Tutorials