Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[groovy]play midi
// groovy sakura.groovy
import javax.sound.midi.*
// compose sequence
ticks = 16
// compose utils
def addNote(track, pitch, start, duration=ticks, velocity=64) {
// pitch: C=60, D=62, E=64, F=65, G=67, A=69, B=71, ...
// start: absolute time
// duration: 1/4 = ticks
// velocity: 0 <= soft < 64 < hard <= 127
// returns: end time
message = new ShortMessage()
message.setMessage(ShortMessage.NOTE_ON, pitch, velocity)
track.add(new MidiEvent(message, start))
message = new ShortMessage()
message.setMessage(ShortMessage.NOTE_OFF, pitch, velocity)
track.add(new MidiEvent(message, start + duration))
return start + duration
}
def instChange(track, instNo=0) {
// instNo: 0-127, default 0
message = new ShortMessage()
message.setMessage(ShortMessage.PROGRAM_CHANGE, 0, instNo, 0)
track.add(new MidiEvent(message, 0))
}
A1=57; B1=59; C1=60; D1=62; E1=64; F1=65; G1=67; A2=69; B2=71; C2=72
d1=ticks*4; d15=ticks*3; d2=ticks*2; d4=ticks; d8=ticks/2 as int
// from http://en.wikipedia.org/wiki/Sakura_Sakura
score = [
[A2, d4], [A2, d4], [B2, d2],
[A2, d4], [A2, d4], [B2, d2],
[A2, d4], [B2, d4], [C2, d4], [B2, d4],
[A2, d4], [B2, d8], [A2, d8], [F1, d2],
[E1, d4], [C1, d4], [E1, d4], [F1, d4],
[E1, d4], [E1, d8], [C1, d8], [B1, d2],
[A2, d4], [B2, d4], [C2, d4], [B2, d4],
[A2, d4], [B2, d8], [A2, d8], [F1, d2],
[E1, d4], [C1, d4], [E1, d4], [F1, d4],
[E1, d4], [E1, d8], [C1, d8], [B1, d2],
[A2, d4], [A2, d4], [B2, d2],
[A2, d4], [A2, d4], [B2, d2],
[E1, d4], [F1, d4], [B2, d8], [A2, d8], [F1, d4],
[E1, d2], [null, d2],
]
// edit track
seq = new Sequence(Sequence.PPQ, ticks)
track = seq.createTrack()
instChange(track, 107)
t = 0
score.each { pitch, duration ->
t = pitch ? addNote(track, pitch, t, duration) : t + duration
}
// play
seqr = MidiSystem.sequencer
seqr.tempoInBPM = 72.0
seqr.sequence = seq
seqr.open()
seqr.start()
while (seqr.isRunning()) Thread.sleep(1000)
seqr.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment