Greetings everyone, I am new to the community but have looked at many other posts and this seems like a very helpful place to newer programmers.
So I am supposed to make a code to output "Twinkle Twinkle Little Star" using a loop/array..... I can do this just fine without trying to loop it with an array but when I do(this is the code I have posted) it just seems like the music scales up rather then play the music like I want it too....other then that it runs fine.
Does anyone have any suggestions on what I could do?
Also what would I have to do to play two instruments at the same time for this song?
Thank you.
Code:import javax.sound.midi.*;
public class MusicB
{
//Method: playNote
//Description: Uses the MidiSynthesizer to play a single note.
//Arguments: int note: note to play (0-127)
// int velocity: the velocity or volume of the note (0-127)
// int duration: length of the note in milliseconds
// MidiChannel: the instruments to play the note
static void playNote(int note, int velocity,int duration, MidiChannel channels[])
{
//start playing the note using instrument in slot 0
channels[0].noteOn(note, velocity);
//wait out the duration
try
{
Thread.sleep(duration);
}
catch (InterruptedException e)
{
}
//stop playing the note
channels[0].noteOff(note);
}
public static void main(String[] args)
{
// Initialize the synthesizer
Synthesizer synth = null;
try {
synth = MidiSystem.getSynthesizer();
}
catch (MidiUnavailableException e) { }
try
{
synth.open();
}
catch (MidiUnavailableException e)
{
e.printStackTrace();
System.exit(1);
}
// Define array for musical instruments / channels
int notes[] = {60, 60, 67, 67, 69, 69, 67, 65, 65, 64, 64, 62, 62, 61};
int velocities [] = new int [1];
int duration [] = new int [1];
MidiChannel[] channels = synth.getChannels();
Instrument instruments[] = synth.getAvailableInstruments();
// Then pick an instrument to load.
// The following loads instrument number 101 into channel 0
synth.loadInstrument(instruments[0]);
channels[0].programChange(74);
velocities[0] = 127;
duration[0] = 400;
int stop = 0;
// Play notes using the default for the channels
while (stop < 14) {
playNote(notes[0], velocities[0], duration[0], channels);
stop ++;
notes[0] ++;
}
}
}
