Skip to content

Instantly share code, notes, and snippets.

@sharpedavid
Last active December 8, 2023 23:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharpedavid/8ec3e0e6cfee0b2a7b6fcf94bf57ac5d to your computer and use it in GitHub Desktop.
Save sharpedavid/8ec3e0e6cfee0b2a7b6fcf94bf57ac5d to your computer and use it in GitHub Desktop.
import javax.sound.midi.*;
class MidiTunePlayer {
public static void main(String[] args) {
try {
// Get a sequencer and open it
Sequencer sequencer = MidiSystem.getSequencer();
sequencer.open();
// Create a sequence and a track
Sequence sequence = new Sequence(Sequence.PPQ, 4);
Track track = sequence.createTrack();
// Add notes to the track
int[] notes; // Initialize the notes array
String tuneType = "dramatic"; // Change this to "dramatic" for the dramatic tune
if ("sad".equals(tuneType)) {
notes = new int[]{69, 67, 65, 64, 62, 60, 62, 64, 65, 67, 69, 67, 65, 64, 62, 60}; // Extended A minor scale
} else if ("dramatic".equals(tuneType)) {
notes = new int[]{60, 72, 71, 60, 72, 71, 69, 67, 71, 60, 72, 60, 71, 69, 67, 65}; // Extended dramatic scale
} else {
notes = new int[]{60, 62, 64, 65, 67, 69, 71, 72, 60, 62, 64, 65, 67, 69, 71, 72}; // Default to extended C major scale
}
for (int i = 0; i < notes.length; i++) {
track.add(createNoteOnEvent(notes[i], i * 4));
track.add(createNoteOffEvent(notes[i], i * 4 + 4));
}
// Set the sequence on the sequencer and start playing
sequencer.setSequence(sequence);
sequencer.start();
// Give enough time for the sequence to play
Thread.sleep(10000);
// Close the sequencer
sequencer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static MidiEvent createNoteOnEvent(int nKey, long lTick) {
return createNoteEvent(ShortMessage.NOTE_ON, nKey, 93, lTick);
}
private static MidiEvent createNoteOffEvent(int nKey, long lTick) {
return createNoteEvent(ShortMessage.NOTE_OFF, nKey, 0, lTick);
}
private static MidiEvent createNoteEvent(int nCommand, int nKey, int nVelocity, long lTick) {
MidiEvent event = null;
try {
ShortMessage message = new ShortMessage();
message.setMessage(nCommand, 0, nKey, nVelocity);
event = new MidiEvent(message, lTick);
} catch (InvalidMidiDataException e) {
e.printStackTrace();
}
return event;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment