まだよくわかってないけどkotlinしてみる
import javafx.stage.Stage
import javafx.application.Application
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.layout.BorderPane
import javafx.event.ActionEvent
import javafx.event.EventHandler
import javafx.animation.KeyFrame
import javafx.animation.Timeline
import javafx.animation.Animation
import javafx.util.Duration
import javax.sound.midi.Receiver
import javax.sound.midi.MidiSystem
import javax.sound.midi.ShortMessage
import javax.sound.midi.InvalidMidiDataException
fun main(args: Array<String>){
Application.launch(DrumTest::class.java, *args)
}
class DrumTest() : Application(){
private val receiver: Receiver
private val pattern = "B-S-BBS-"
private var patternIndex = 0
init{
receiver = MidiSystem.getReceiver()
}
override fun start(stage: Stage){
val button = createDrumButton("8ビート!")
val pane = BorderPane()
pane.setCenter(button)
val scene = Scene(pane, 320.0, 120.0)
stage.setScene(scene)
stage.show()
}
private fun createDrumButton(text: String): Button{
val button = Button(text)
val timer = Timeline(KeyFrame(Duration.millis(250.0), object : EventHandler<ActionEvent>{
override fun handle(event: ActionEvent?){
try{
if(pattern[patternIndex] == 'B'){
noteBassDrum();
}else if(pattern[patternIndex] == 'S'){
noteSnareDrum();
}
}catch(ex: InvalidMidiDataException){
ex.printStackTrace();
}
patternIndex = (patternIndex + 1) % 8;
}
}))
button.setOnAction({ _ ->
if(timer.getStatus() == Animation.Status.STOPPED){
timer.setCycleCount(16);
timer.play();
}
})
return button
}
private fun noteBassDrum(){
val message = ShortMessage()
message.setMessage(ShortMessage.NOTE_ON, 9, 36, 100)
receiver.send(message, -1)
}
private fun noteSnareDrum(){
val message = ShortMessage()
message.setMessage(ShortMessage.NOTE_ON, 9, 38, 100)
receiver.send(message, -1)
}
}
参考
qiita.com