Tartalomjegyzék

< Java

Java Midi

Példa

Program01.java
import javax.sound.midi.MidiChannel;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Synthesizer;
 
class Synth {
    Synthesizer synth;
    MidiChannel channel;
    int keyReleasedSpeed;
    int soundLength;
    int instrument;
 
    Synth() {
        init();
    }
 
    public void init() {
        try {
            tryInit();
        }catch(MidiUnavailableException ex) {
            System.err.println("Nincs Midi!");
        }       
    }
 
    public void tryInit() throws MidiUnavailableException{
        synth = MidiSystem.getSynthesizer();
        synth.open();
        //chanels 0-9
        channel = synth.getChannels()[0];
        this.keyReleasedSpeed = 80;
        this.soundLength = 1000;
        this.instrument = 0;
    }
 
    public void play(int note) {
        try {
            tryPlay(note);
        }catch(InterruptedException ex) {
            System.err.println("Hiba a várakozásnál!");
        }
    }
 
    public void tryPlay(int note) 
            throws InterruptedException {
 
        channel.programChange(this.instrument);        
        channel.noteOn(note, this.keyReleasedSpeed);
        Thread.sleep(this.soundLength);
        channel.noteOff(note);
    }
 
    public void close() {
        synth.close();
    }
 
    public void setInstrument(int instrument) {
        // instruments 0 - 127
        this.instrument = instrument;
    }
 
}
 
public class HangProba {    
    public static void main(String[] args) {
        Synth synth = new Synth();
        synth.setInstrument(10);
 
        for (int i = 60; i < 70; i++) {
            System.out.println(i);
            synth.play(i);
        }
        synth.close();
    }    
}

Linkek