Hello,

I am pretty new to Java so I am following along in a book to learn it. I am currently in the beginnings of making a MIDI player but I have run into to a problem. I am using a sequencer, if I don't close the sequencer the program will run the midi sound but will not exit. However if I do close the sequencer the program completes but will not play the sound. Any help would be appreciated.

import javax.sound.midi.*;

public class MiniMusicCmdLine
{
    public static void main (String [] args)
    {
        MiniMusicCmdLine mini = new MiniMusicCmdLine ();
        if (args.length < 2)
        {
            System.out.println ("Two arguements dude!!!");
        }
        else
        {
            int instrument = Integer.parseInt (args[0]);
            int note = Integer.parseInt (args[1]);
            mini.play (instrument, note);
        }
    }
    
    public void play (int instrument, int note)
    {
        try
        {
            Sequencer player = MidiSystem.getSequencer ();
            player.open ();
            Sequence seq = new Sequence (Sequence.PPQ, 4);
            Track track = seq.createTrack ();
            
            ShortMessage first = new ShortMessage ();
            first.setMessage (192,1, instrument, 0);
            MidiEvent changeInstrument = new MidiEvent (first, 1);
            track.add (changeInstrument);
            
            ShortMessage a = new ShortMessage ();
            a.setMessage (144, 1, note, 100);
            MidiEvent noteOn = new MidiEvent (a, 1);
            track.add (noteOn);
            
            ShortMessage b = new ShortMessage ();
            b.setMessage (128, 1, note, 100);
            MidiEvent noteOff = new MidiEvent (b, 16);
            track.add (noteOff);
            player.setSequence (seq);
            player.start ();
        }
        catch (Exception ex)
        {
            ex.printStackTrace ();
        }
    }
}

By the way I had this problem when using my mac (I say this because every similar problem I found was always on a mac) Anyway, turns out I need to use Thread.sleep (5000) with the 5000 representing miliseconds to give the player time finish its thing.

// something like this
player.start ();
Thread.sleep (5000);
player.close ();
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.