0

I want to play a single, random note in Java. I use the following:

Random rand = new Random();

try {
    Synthesizer synth = MidiSystem.getSynthesizer();
    synth.open();

    int note = rand.nextInt(128);
    channels[0].noteOn(note, 80);
} catch (MidiUnavailableException e) {
    e.printStackTrace();
}

but nothing ever happens. Can anyone tell me why?

EDIT: I forgot to include MidiChannel[] channels = synth.getChannels();

ricky3350
  • 1,710
  • 3
  • 20
  • 35
  • 2
    Where is channels defined? I would expect a line of code such as: MidiChannel[] channels = synth.getChannels(); - also, is your program exiting before the note has time to play? – slipperyseal Jan 12 '15 at 02:16

1 Answers1

1

What's channels[0] set to? Since you say "nothing happens" I'm assuming that the program is running and not throwing a NullPointerException, which means channels[0] has to have a non-null value. I'll bet you forgot to link your existing channels[0] object to your synth object somehow. Sorry for a non-specific answer, I'll dig a bit more into the API.

EDIT: Ok, try changing channels[0] to synth.getChannels()[0]:

    Random rand = new Random();

    try {
        Synthesizer synth = MidiSystem.getSynthesizer();
        synth.open();

        int note = rand.nextInt(128);
        synth.getChannels()[0].noteOn(note, 80);
    } catch (MidiUnavailableException e) {
        e.printStackTrace();
    }

I got this to play a random note.

James Cronen
  • 5,715
  • 2
  • 32
  • 52
  • Unfortunately, my computer stays silent. Sorry about forgetting that code line. – ricky3350 Jan 12 '15 at 13:17
  • Is there some other device "using" that channel (i.e., can you unplug all MIDI devices)? Can you try changing the index to `[1]`, `[2]`, etc.? – James Cronen Jan 12 '15 at 14:16
  • All channels are silent. – ricky3350 Jan 12 '15 at 20:09
  • If you copy&paste this in main function, the synthesizer will be closed before it plays any note. This could use some thread.sleep or other wait mechanism to play a note. – Marcin Jun 22 '18 at 07:41