ITeye博客

用JRuby写个小MIDI

googya · 2009-08-21 10:47 · JRuby&Ruby · 编程语言 · Markdown

include Java
 
include_class javax.sound.midi.MidiSystem
include_class javax.swing.JFrame
include_class java.awt.event.KeyListener
 
# 准备合成
hecheng = MidiSystem.synthesizer
hecheng.open
channel = hecheng.channels[0]
 
# 接收按键的frame
midi_frame = JFrame.new("Music Frame")
midi_frame.set_size 200, 200
midi_frame.default_close_operation = JFrame::EXIT_ON_CLOSE
 
# 监听键盘
midi_frame.add_key_listener KeyListener.impl { |name, event|
  case name
  when :keyPressed
    channel.note_on event.key_char, 64
  when :keyReleased
    channel.note_off event.key_char
  end
}
 
# 显示 midi_frame
midi_frame.visible = true
这样写一个MIDI是不是比Java写的简单很多,也简洁很多?
值得注意的一个小地方是,关于接口的实现。在较新版本的JRuby中,接口一般是当做模块混含进JRuby的。但是同时JRuby提供了一个接口的实现方法 impl。
这样我觉得是更加简洁了,而且有匿名类的效果。

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。