预期行为:中间 C 在一个 midi 乐器上演奏,然后是另一个。实际行为:DL 弃用警告并且没有声音。运行 Windows 7。
编码:
require "dl/import"
class LiveMIDI
ON = 0x90
OFF =0x80
PC = 0xc0
def initialize
open
end
def note_on(channel, note, velocity=64)
message(ON | channel, note, velocity)
end
def note_off(channel, note, velocity=64)
message(OFF | channel, note, velocity)
end
def program_change(channel, preset)
message(PC | channel, preset)
end
module C
extend DL::Importer
dlload "winmm"
extern "int midiOutOpen(HMIDIOUT*, int, int, int, int)"
extern "int midiOutClose(int)"
extern "int midiOutShortMsg(int, int)"
end
def open
@device = DL.malloc(DL::Importer.sizeof("int"))
C.midiOutOpen(@device, -1, 0, 0, 0)
end
def close
C.midiOutClose(@device.ptr.to_i)
end
def message(one, two=0, three=0)
message = one + (two << 8) + (three << 16)
C.midiOutShortMsg(DL::CPtr.to_ptr(@device).to_i, message)
end
end
midi = LiveMIDI.new
midi.note_on(0, 60, 100)
sleep(1)
midi.note_off(0, 60)
midi.program_change(1, 40)
midi.note_on(1, 60, 100)
sleep(1)
midi.note_off(1, 60)
摘自《实用 Ruby 项目》一书。根据第 2 章 11-15 页上的数字。代码稍作修改以处理 Ruby 1.9 中对 Ruby DL 的更改。