Java Midi-在演奏时如何从Midi获取笔记 [英] Java Midi - How to get notes from midi whilst it's playing

查看:106
本文介绍了Java Midi-在演奏时如何从Midi获取笔记的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了一段时间,但找不到我想要做什么的答案.

I've searched for a while now, and can't find an answer for what I want to do.

我要播放一个midi文件,并在播放时在屏幕上显示笔记.当音符停止播放时,它应该会从屏幕上消失.

I want to play a midi file, and display the notes on the screen as it plays. When a note stops playing, it should disappear off the screen.

我可以用音序器演奏Midi,但是不知道如何演奏它的音符,或者不知道何时停止演奏音符.

I can play a midi with a sequencer, but have no idea of how to get the notes its playing, or when it stops playing a note.

我已经研究了ControllerEventListeners和MetaEventListeners,但仍然不知道该怎么做.

I've looked into ControllerEventListeners and MetaEventListeners, but still don't know how to do this.

任何帮助将不胜感激.

推荐答案

这就是您应该做的:

您必须先实现Receiver,然后实现

You have to implement Receiver and then

sequencer = MidiSystem.getSequencer();
sequencer.open();
transmitter = sequencer.getTransmitter();
transmitter.setReceiver(this);

然后,每次事件发生时都会触发下一个方法:

and after that, the next method will be triggered every time an event occurs:

@Override
public void send(MidiMessage message, long timeStamp) {
    if(message instanceof ShortMessage) {
        ShortMessage sm = (ShortMessage) message;
        int channel = sm.getChannel();

        if (sm.getCommand() == NOTE_ON) {

            int key = sm.getData1();
            int velocity = sm.getData2();
            Note note = new Note(key);
            System.out.println(note);

        } else if (sm.getCommand() == NOTE_OFF) {

            int key = sm.getData1();
            int velocity = sm.getData2();
            Note note = new Note(key);
            System.out.println(note);
        } else {
            System.out.println("Command:" + sm.getCommand());
        }
    }
}

如果需要,您也可以使用此类:

and if you want, you can use this class too:

public class Note {

    private static final String[] NOTE_NAMES = {"C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"};

    private String name;
    private int key;
    private int octave;

    public Note(int key) {
        this.key = key;
        this.octave = (key / 12)-1;
        int note = key % 12;
        this.name = NOTE_NAMES[note];
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof Note && this.key == ((Note) obj).key;
    }

    @Override
    public String toString() {
        return "Note -> " + this.name + this.octave + " key=" + this.key;
    }
}

这篇关于Java Midi-在演奏时如何从Midi获取笔记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆