Example usage for javax.sound.midi MidiSystem getSequencer

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

Introduction

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

Prototype

public static Sequencer getSequencer() throws MidiUnavailableException 

Source Link

Document

Obtains the default Sequencer , connected to a default device.

Usage

From source file:MidiTest.java

/**
 * Creates a new MidiPlayer object.//from ww  w .  j a  v  a 2s  .  c om
 */
public MidiPlayer() {
    try {
        sequencer = MidiSystem.getSequencer();
        sequencer.open();
        sequencer.addMetaEventListener(this);
    } catch (MidiUnavailableException ex) {
        sequencer = null;
    }
}

From source file:SimpleSoundPlayer.java

public void open() {
    try {//from w w w.j  ava  2 s. c  o m
        sequencer = MidiSystem.getSequencer();

        if (sequencer instanceof Synthesizer) {
            synthesizer = (Synthesizer) sequencer;
            channels = synthesizer.getChannels();
        }

    } catch (Exception ex) {
        ex.printStackTrace();
        return;
    }
    sequencer.addMetaEventListener(this);

}

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;//from  www  .  j  a  v a2 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:Main.java

public static void streamMidiSequence(URL url)
        throws IOException, InvalidMidiDataException, MidiUnavailableException {
    Sequencer sequencer = null; // Converts a Sequence to MIDI events
    Synthesizer synthesizer = null; // Plays notes in response to MIDI events

    try {//from w  w  w .j  ava2  s . c o  m
        // Create, open, and connect a Sequencer and Synthesizer
        // They are closed in the finally block at the end of this method.
        sequencer = MidiSystem.getSequencer();
        sequencer.open();
        synthesizer = MidiSystem.getSynthesizer();
        synthesizer.open();
        sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());

        // Specify the InputStream to stream the sequence from
        sequencer.setSequence(url.openStream());

        // This is an arbitrary object used with wait and notify to
        // prevent the method from returning before the music finishes
        final Object lock = new Object();

        // Register a listener to make the method exit when the stream is
        // done. See Object.wait() and Object.notify()
        sequencer.addMetaEventListener(new MetaEventListener() {
            public void meta(MetaMessage e) {
                if (e.getType() == END_OF_TRACK) {
                    synchronized (lock) {
                        lock.notify();
                    }
                }
            }
        });

        // Start playing the music
        sequencer.start();

        // Now block until the listener above notifies us that we're done.
        synchronized (lock) {
            while (sequencer.isRunning()) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                }
            }
        }
    } finally {
        // Always relinquish the sequencer, so others can use it.
        if (sequencer != null)
            sequencer.close();
        if (synthesizer != null)
            synthesizer.close();
    }
}

From source file:edu.tsinghua.lumaqq.Sounder.java

/**
 * ?/*from  ww  w .j a v  a2 s  . c o  m*/
 */
public void openSequencer() {
    try {
        sequencer = MidiSystem.getSequencer();
        sequencer.addMetaEventListener(this);
    } catch (Exception ex) {
        log.error("Midi Sequencer?");
        sequencer = null;
        return;
    }
}

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;/*from   ww w  .  j a  v  a 2  s. com*/

    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;/*from w ww .  j a v  a2  s.co 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("??????");
    }//  w  ww .  jav  a  2s . 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("??");
}

From source file:tvbrowser.extras.reminderplugin.ReminderPlugin.java

/**
 * Plays a sound.//  w  w w  .j  av a 2s  .c o  m
 *
 * @param fileName
 *          The file name of the sound to play.
 * @return The sound Object.
 */
public static Object playSound(final String fileName) {
    try {
        if (StringUtils.endsWithIgnoreCase(fileName, ".mid")) {
            final Sequencer sequencer = MidiSystem.getSequencer();
            sequencer.open();

            final InputStream midiFile = new FileInputStream(fileName);
            sequencer.setSequence(MidiSystem.getSequence(midiFile));

            sequencer.start();

            new Thread("Reminder MIDI sequencer") {
                @Override
                public void run() {
                    setPriority(Thread.MIN_PRIORITY);
                    while (sequencer.isRunning()) {
                        try {
                            Thread.sleep(100);
                        } catch (Exception ee) {
                            // ignore
                        }
                    }

                    try {
                        sequencer.close();
                        midiFile.close();
                    } catch (Exception ee) {
                        // ignore
                    }
                }
            }.start();

            return sequencer;
        } else {
            final AudioInputStream ais = AudioSystem.getAudioInputStream(new File(fileName));

            final AudioFormat format = ais.getFormat();
            final DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

            if (AudioSystem.isLineSupported(info)) {
                final SourceDataLine line = (SourceDataLine) AudioSystem.getLine(info);

                line.open(format);
                line.start();

                new Thread("Reminder audio playing") {
                    private boolean stopped;

                    @Override
                    public void run() {
                        byte[] myData = new byte[1024 * format.getFrameSize()];
                        int numBytesToRead = myData.length;
                        int numBytesRead = 0;
                        int total = 0;
                        int totalToRead = (int) (format.getFrameSize() * ais.getFrameLength());
                        stopped = false;

                        line.addLineListener(new LineListener() {
                            public void update(LineEvent event) {
                                if (line != null && !line.isRunning()) {
                                    stopped = true;
                                    line.close();
                                    try {
                                        ais.close();
                                    } catch (Exception ee) {
                                        // ignore
                                    }
                                }
                            }
                        });

                        try {
                            while (total < totalToRead && !stopped) {
                                numBytesRead = ais.read(myData, 0, numBytesToRead);

                                if (numBytesRead == -1) {
                                    break;
                                }

                                total += numBytesRead;
                                line.write(myData, 0, numBytesRead);
                            }
                        } catch (Exception e) {
                        }

                        line.drain();
                        line.stop();
                    }
                }.start();

                return line;
            } else {
                URL url = new File(fileName).toURI().toURL();
                AudioClip clip = Applet.newAudioClip(url);
                clip.play();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        if ((new File(fileName)).isFile()) {
            URL url;
            try {
                url = new File(fileName).toURI().toURL();
                AudioClip clip = Applet.newAudioClip(url);
                clip.play();
            } catch (MalformedURLException e1) {
            }
        } else {
            String msg = mLocalizer.msg("error.1", "Error loading reminder sound file!\n({0})", fileName);
            JOptionPane.showMessageDialog(UiUtilities.getBestDialogParent(MainFrame.getInstance()), msg,
                    Localizer.getLocalization(Localizer.I18N_ERROR), JOptionPane.ERROR_MESSAGE);
        }
    }
    return null;
}