カテゴリー
Android Java

AndroidでMidiで音を出してみた

import cn.sherlock.com.sun.media.sound.SF2Soundbank;
import cn.sherlock.com.sun.media.sound.SoftSynthesizer;
import jp.kshoji.javax.sound.midi.InvalidMidiDataException;
import jp.kshoji.javax.sound.midi.MidiSystem;
import jp.kshoji.javax.sound.midi.MidiUnavailableException;
import jp.kshoji.javax.sound.midi.Receiver;
import jp.kshoji.javax.sound.midi.ShortMessage;
// minimum setup for playing notes without using a Sequencer
// it plays random 3rd dyad each time
SF2Soundbank sf = new SF2Soundbank(getAssets().open("steinway.sf2"));
SoftSynthesizer synth = new SoftSynthesizer();
synth.open();
synth.loadAllInstruments(sf);
Receiver recv = synth.getReceiver;
ShortMessage msg = new ShortMessage();
int max = 72;
int min = 36;
int num = (int)Math.floor(Math.random()*(max-min)+min);
try {
  msg.setMessage(ShortMessage.NOTE_ON, 0, num, 127);
  recv.send(msg, synth.getMicrosecondPosition());
  msg.setMessage(ShortMessage.NOTE_ON, 0, num+4, 127);
  recv.send(msg, synth.getMicrosecondPosition());
}