Example usage for javax.sound.midi MidiSystem getSequence

List of usage examples for javax.sound.midi MidiSystem getSequence

Introduction

In this page you can find the example usage for javax.sound.midi MidiSystem getSequence.

Prototype

public static Sequence getSequence(final File file) throws InvalidMidiDataException, IOException 

Source Link

Document

Obtains a MIDI sequence from the specified File .

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Sequence sequence = MidiSystem.getSequence(new File("midiaudiofile"));

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

    // Create a sequencer for the sequence
    Sequencer sequencer = MidiSystem.getSequencer();
    sequencer.open();//from w  w w.j av a  2  s . c o  m
    sequencer.setSequence(sequence);

    double durationInSecs = sequencer.getMicrosecondLength() / 1000000.0;

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    Sequence sequence = MidiSystem.getSequence(new File("midifile"));

    // From URL/*from www . j  av  a  2 s .c o  m*/
    sequence = MidiSystem.getSequence(new URL("http://hostname/midifile"));

    // Create a sequencer for the sequence
    Sequencer sequencer = MidiSystem.getSequencer();
    sequencer.open();
    sequencer.setSequence(sequence);

    // Start playing
    sequencer.start();
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    // From file/* w  w w.j  a  v  a 2s  .  c  o  m*/
    Sequence sequence = MidiSystem.getSequence(new File("midiaudiofile"));

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

    // Create a sequencer for the sequence
    Sequencer sequencer = MidiSystem.getSequencer();
    sequencer.open();
    sequencer.setSequence(sequence);

    // Start playing
    sequencer.start();
}

From source file:com.foudroyantfactotum.mod.fousarchive.midi.generation.MidiImageGeneration.java

public MidiImageGeneration(InputStream addr, int imgX, int imgY) throws InvalidMidiDataException, IOException {
    sequencer = MidiSystem.getSequence(addr);

    this.imgX = imgX;
    this.imgY = imgY;
}

From source file:MidiTest.java

/**
 * Loads a sequence from an input stream. Returns null if an error occurs.
 *//*from   ww  w. j  a v  a  2  s .co  m*/
public Sequence getSequence(InputStream is) {
    try {
        if (!is.markSupported()) {
            is = new BufferedInputStream(is);
        }
        Sequence s = MidiSystem.getSequence(is);
        is.close();
        return s;
    } catch (InvalidMidiDataException ex) {
        ex.printStackTrace();
        return null;
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:SoundPlayer.java

public SoundPlayer(File f, boolean isMidi) throws IOException, UnsupportedAudioFileException,
        LineUnavailableException, MidiUnavailableException, InvalidMidiDataException {
    if (isMidi) { // The file is a MIDI file
        midi = true;/*w w w.  j av a 2  s.c  o m*/
        // First, get a Sequencer to play sequences of MIDI events
        // That is, to send events to a Synthesizer at the right time.
        sequencer = MidiSystem.getSequencer(); // Used to play sequences
        sequencer.open(); // Turn it on.

        // Get a Synthesizer for the Sequencer to send notes to
        Synthesizer synth = MidiSystem.getSynthesizer();
        synth.open(); // acquire whatever resources it needs

        // The Sequencer obtained above may be connected to a Synthesizer
        // by default, or it may not. Therefore, we explicitly connect it.
        Transmitter transmitter = sequencer.getTransmitter();
        Receiver receiver = synth.getReceiver();
        transmitter.setReceiver(receiver);

        // Read the sequence from the file and tell the sequencer about it
        sequence = MidiSystem.getSequence(f);
        sequencer.setSequence(sequence);
        audioLength = (int) sequence.getTickLength(); // Get sequence length
    } else { // The file is sampled audio
        midi = false;
        // Getting a Clip object for a file of sampled audio data is kind
        // of cumbersome. The following lines do what we need.
        AudioInputStream ain = AudioSystem.getAudioInputStream(f);
        try {
            DataLine.Info info = new DataLine.Info(Clip.class, ain.getFormat());
            clip = (Clip) AudioSystem.getLine(info);
            clip.open(ain);
        } finally { // We're done with the input stream.
            ain.close();
        }
        // Get the clip length in microseconds and convert to milliseconds
        audioLength = (int) (clip.getMicrosecondLength() / 1000);
    }

    // Now create the basic GUI
    play = new JButton("Play"); // Play/stop button
    progress = new JSlider(0, audioLength, 0); // Shows position in sound
    time = new JLabel("0"); // Shows position as a #

    // When clicked, start or stop playing the sound
    play.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (playing)
                stop();
            else
                play();
        }
    });

    // Whenever the slider value changes, first update the time label.
    // Next, if we're not already at the new position, skip to it.
    progress.addChangeListener(new ChangeListener() {
        public void stateChanged(ChangeEvent e) {
            int value = progress.getValue();
            // Update the time label
            if (midi)
                time.setText(value + "");
            else
                time.setText(value / 1000 + "." + (value % 1000) / 100);
            // If we're not already there, skip there.
            if (value != audioPosition)
                skip(value);
        }
    });

    // This timer calls the tick() method 10 times a second to keep
    // our slider in sync with the music.
    timer = new javax.swing.Timer(100, new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            tick();
        }
    });

    // put those controls in a row
    Box row = Box.createHorizontalBox();
    row.add(play);
    row.add(progress);
    row.add(time);

    // And add them to this component.
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
    this.add(row);

    // Now add additional controls based on the type of the sound
    if (midi)
        addMidiControls();
    else
        addSampledControls();
}

From source file:at.ofai.music.util.WormFileParseException.java

public static EventList readMidiFile(String fileName, int skipTrackFlag) {
    EventList list = new EventList();
    Sequence s;//from   w ww .  j  av  a  2  s.c  om
    try {
        s = MidiSystem.getSequence(new File(fileName));
    } catch (Exception e) {
        e.printStackTrace();
        return list;
    }
    double midiTempo = 500000;
    double tempoFactor = midiTempo / s.getResolution() / 1000000.0;
    // System.err.println(tempoFactor);
    Event[][] noteOns = new Event[128][16];
    Track[] tracks = s.getTracks();
    for (int t = 0; t < tracks.length; t++, skipTrackFlag >>= 1) {
        if ((skipTrackFlag & 1) == 1)
            continue;
        for (int e = 0; e < tracks[t].size(); e++) {
            MidiEvent me = tracks[t].get(e);
            MidiMessage mm = me.getMessage();
            double time = me.getTick() * tempoFactor;
            byte[] mesg = mm.getMessage();
            int channel = mesg[0] & 0x0F;
            int command = mesg[0] & 0xF0;
            if (command == ShortMessage.NOTE_ON) {
                int pitch = mesg[1] & 0x7F;
                int velocity = mesg[2] & 0x7F;
                if (noteOns[pitch][channel] != null) {
                    if (velocity == 0) { // NOTE_OFF in disguise :(
                        noteOns[pitch][channel].keyUp = time;
                        noteOns[pitch][channel].pedalUp = time;
                        noteOns[pitch][channel] = null;
                    } else
                        System.err.println("Double note on: n=" + pitch + " c=" + channel + " t1="
                                + noteOns[pitch][channel] + " t2=" + time);
                } else {
                    Event n = new Event(time, 0, 0, pitch, velocity, -1, -1, 0, ShortMessage.NOTE_ON, channel,
                            t);
                    noteOns[pitch][channel] = n;
                    list.add(n);
                }
            } else if (command == ShortMessage.NOTE_OFF) {
                int pitch = mesg[1] & 0x7F;
                noteOns[pitch][channel].keyUp = time;
                noteOns[pitch][channel].pedalUp = time;
                noteOns[pitch][channel] = null;
            } else if (command == 0xF0) {
                if ((channel == 0x0F) && (mesg[1] == 0x51)) {
                    midiTempo = (mesg[5] & 0xFF) | ((mesg[4] & 0xFF) << 8) | ((mesg[3] & 0xFF) << 16);
                    tempoFactor = midiTempo / s.getResolution() / 1000000.0;
                    //   System.err.println("Info: Tempo change: " + midiTempo +
                    //                  "  tf=" + tempoFactor);
                }
            } else if (mesg.length > 3) {
                System.err.println("midi message too long: " + mesg.length);
                System.err.println("\tFirst byte: " + mesg[0]);
            } else {
                int b0 = mesg[0] & 0xFF;
                int b1 = -1;
                int b2 = -1;
                if (mesg.length > 1)
                    b1 = mesg[1] & 0xFF;
                if (mesg.length > 2)
                    b2 = mesg[2] & 0xFF;
                list.add(new Event(time, time, -1, b1, b2, -1, -1, 0, b0 & 0xF0, b0 & 0x0F, t));
            }
        }
    }
    for (int pitch = 0; pitch < 128; pitch++)
        for (int channel = 0; channel < 16; channel++)
            if (noteOns[pitch][channel] != null)
                System.err.println("Missing note off: n=" + noteOns[pitch][channel].midiPitch + " t="
                        + noteOns[pitch][channel].keyDown);
    return list;
}

From source file:org.wso2.carbon.device.mgt.iot.agent.firealarm.virtual.VirtualHardwareManager.java

private void setAudioSequencer() {
    InputStream audioSrc = AgentUtilOperations.class.getResourceAsStream("/" + AgentConstants.AUDIO_FILE_NAME);
    Sequence sequence;/*  ww w.ja  va2s.  c o  m*/

    try {
        sequence = MidiSystem.getSequence(audioSrc);
        sequencer = MidiSystem.getSequencer();
        sequencer.open();
        sequencer.setSequence(sequence);
    } catch (InvalidMidiDataException e) {
        log.error("AudioReader: Error whilst setting MIDI Audio reader sequence");
    } catch (IOException e) {
        log.error("AudioReader: Error whilst getting audio sequence from stream");
    } catch (MidiUnavailableException e) {
        log.error("AudioReader: Error whilst openning MIDI Audio reader sequencer");
    }

    sequencer.setLoopCount(Clip.LOOP_CONTINUOUSLY);
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.virtual.VirtualHardwareManager.java

private void setAudioSequencer() {
    InputStream audioSrc = AgentUtilOperations.class.getResourceAsStream("/" + AgentConstants.AUDIO_FILE_NAME);
    Sequence sequence;/*  ww w  . j  av  a  2  s.  c  o  m*/

    try {
        sequence = MidiSystem.getSequence(audioSrc);
        sequencer = MidiSystem.getSequencer();
        if (sequencer != null) {
            sequencer.open();
            sequencer.setSequence(sequence);
            sequencer.setLoopCount(Clip.LOOP_CONTINUOUSLY);
        }
    } catch (InvalidMidiDataException e) {
        log.error("AudioReader: Error whilst setting MIDI Audio reader sequence");
    } catch (IOException e) {
        log.error("AudioReader: Error whilst getting audio sequence from stream");
    } catch (MidiUnavailableException e) {
        log.error("AudioReader: Error whilst openning MIDI Audio reader sequencer");
    }
}

From source file:playmidi.task.MidiPlayTask.java

public MidiPlayTask(File midiFile, int count)
        throws FileNotFoundException, IOException, MidiUnavailableException, InvalidMidiDataException {

    this.midiFile = midiFile;
    this.loopCount = count;

    if (this.midiFile == null) {
        throw new NullPointerException("??????");
    }// www .  ja v  a2  s  .c o m
    if (!midiFile.exists()) {
        MessageFormat msg1 = new MessageFormat("?????File={0}");
        Object[] parameters1 = { this.midiFile.getAbsolutePath() };
        throw new FileNotFoundException(msg1.format(parameters1));
    }
    if (!midiFile.isFile()) {
        MessageFormat msg1 = new MessageFormat("?????File={0}");
        Object[] parameters1 = { this.midiFile.getAbsolutePath() };
        throw new IllegalArgumentException(msg1.format(parameters1));
    }
    if (!midiFile.canRead()) {
        MessageFormat msg1 = new MessageFormat("?????File={0}");
        Object[] parameters1 = { this.midiFile.getAbsolutePath() };
        throw new IllegalArgumentException(msg1.format(parameters1));
    }
    MessageFormat msg1 = new MessageFormat("File={0},LoopCount={1}");
    Object[] parameters1 = { this.midiFile.getAbsolutePath(), loopCount };
    LOG.info(msg1.format(parameters1));

    LOG.trace("?");
    sequencer = MidiSystem.getSequencer();
    sequencer.setLoopEndPoint(-1L);
    sequencer.setLoopCount(loopCount);
    sequencer.open();
    LOG.trace("?");

    LOG.trace("??");
    try (FileInputStream in = new FileInputStream(this.midiFile)) {
        Sequence sequence = MidiSystem.getSequence(in);
        sequencer.setLoopCount(count);
        sequencer.setSequence(sequence);
    }
    LOG.trace("??");
}