|
| 1 | +using PortMidi, MusicTheory |
| 2 | +using MusicTheory.PitchNames |
| 3 | + |
| 4 | +Pm_Initialize() |
| 5 | + |
| 6 | +# 0. Get info about devices |
| 7 | +for i in 0:Pm_CountDevices()-1 |
| 8 | + info = unsafe_load(Pm_GetDeviceInfo(i)) |
| 9 | + if info.input == 0 |
| 10 | + println(i, ": ", unsafe_string(info.name)) |
| 11 | + end |
| 12 | +end |
| 13 | + |
| 14 | +# 1. Select device |
| 15 | +id = 7 # change this number if needed |
| 16 | +print("Use: ", unsafe_string(unsafe_load(Pm_GetDeviceInfo(id)).name)) |
| 17 | + |
| 18 | +# 2. Open device |
| 19 | +stream = Ref{Ptr{PortMidi.PortMidiStream}}(C_NULL) |
| 20 | +Pm_OpenOutput(stream, id, C_NULL, 0, C_NULL, C_NULL, 0) |
| 21 | +# don't forget to call later: Pm_Close(stream[]) |
| 22 | + |
| 23 | +# 3. Send MIDI messages to play notes |
| 24 | +Note_ON = 0x90 |
| 25 | +Note_OFF = 0x80 |
| 26 | +function play_note(stream, note, velocity, duration, delay = 0) |
| 27 | + sleep(delay) |
| 28 | + Pm_WriteShort(stream[], 0, Pm_Message(Note_ON, semitone(note), velocity)) |
| 29 | + sleep(duration) |
| 30 | + Pm_WriteShort(stream[], 0, Pm_Message(Note_OFF, semitone(note), velocity)) |
| 31 | +end |
| 32 | + |
| 33 | +# make a random tune using MusicTheory.jl |
| 34 | +scale = Scale(D[3], major_scale) |
| 35 | +notes = Iterators.take(scale, 14) |> collect |
| 36 | +begin |
| 37 | + N = 100 |
| 38 | + offset = 0.99 |
| 39 | + beat = 0.45 # ms |
| 40 | + |
| 41 | + @async for i in 1:N |
| 42 | + nt = rand(notes) |
| 43 | + rand() < 0.9 && @async play_note(stream, nt, rand(80:120), beat * (0.9 + 0.05*rand())) |
| 44 | + sleep(beat * (1 + 0.001*rand())) |
| 45 | + end |
| 46 | + |
| 47 | + @async for i in 1:N |
| 48 | + nt = rand(notes) |
| 49 | + rand() < 0.9 && @async play_note(stream, nt, rand(80:120), beat * offset* (0.9 + 0.05*rand())) |
| 50 | + sleep(beat * offset * (1 + 0.001*rand())) |
| 51 | + end |
| 52 | +end |
| 53 | + |
| 54 | +# 4. Close device |
| 55 | +Pm_Close(stream[]) |
0 commit comments