---
title: "用JRuby写个小MIDI"
author: "googya"
date: "2009-08-21T10:47:39Z"
tags: []
categories: ["编程语言"]
slug: "jruby-midi"
draft: false
lastmod: "2009-08-21T10:47:39Z"
id: 454245
url: "https://googya.iteye.com/blog/454245"
---

```ruby
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。
    这样我觉得是更加简洁了，而且有匿名类的效果。