如何使用Web MIDI处理设备的插入/拔出?

时间:2018-08-29 19:40:42

标签: javascript web midi web-midi

我正在从事在线乐谱阅读培训师a prototype is available here。我能够实现对先前连接的MIDI键盘的访问,但是,我在努力实现热插拔场景。

我最后一次拍摄如下:

    setupDevices(inputs){
    let deviceName = '';

    inputs.forEach((value, key, map) => {
        if (value.connection === 'open' || value.connection === 'pending' ){

            value.open().then((midiInput) => {
                console.log(`Opened ${midiInput.name}`);
                midiInput.onmidimessage = midiController.onMIDIMessage;
            }, null);
        } else {
            value.onmidimessage = null;
        }
    });

    if (deviceName.length === 0) {
        deviceName = 'none';
    }

    document.getElementById('connectedDevice').setAttribute('value', deviceName);
},

onMIDISuccess(midiAccess) {
    midiAccess.onstatechange = (evt) => {
        console.log('MIDI config changed');
        midiController.setupDevices(evt.currentTarget.inputs);
    };
}

在调试时,所有的Promise都带有漂亮的参数,但是我无法收到任何按键消息。而且console.log(Opened ${midiInput.name})的调用次数比预期的还要多:

midiController.js:57 MIDI config changed
midiController.js:40 Opened KOMPLETE KONTROL - 1
midiController.js:57 MIDI config changed
midiController.js:40 Opened KOMPLETE KONTROL - 1
midiController.js:57 MIDI config changed
midiController.js:40 Opened KOMPLETE KONTROL - 1
midiController.js:40 Opened KOMPLETE KONTROL EXT - 1
midiController.js:40 Opened KOMPLETE KONTROL - 1
3
midiController.js:40 Opened KOMPLETE KONTROL EXT - 1
midiController.js:57 MIDI config changed
midiController.js:40 Opened KOMPLETE KONTROL - 1
midiController.js:40 Opened KOMPLETE KONTROL EXT - 1
midiController.js:57 MIDI config changed
midiController.js:40 Opened KOMPLETE KONTROL - 1
midiController.js:40 Opened KOMPLETE KONTROL EXT - 1
2
midiController.js:40 Opened Komplete Kontrol DAW - 1
midiController.js:57 MIDI config changed
midiController.js:40 Opened KOMPLETE KONTROL - 1
midiController.js:40 Opened KOMPLETE KONTROL EXT - 1
midiController.js:57 MIDI config changed
midiController.js:40 Opened KOMPLETE KONTROL - 1
midiController.js:40 Opened KOMPLETE KONTROL EXT - 1

(所有这些都在我刚打开控制器后立即打印)。有提示吗?

1 个答案:

答案 0 :(得分:0)

function midiOnMIDImessage(event) {
        console.log(event);
    }
function requestMIDIAccessSuccess(midi) {
        var inputs = midi.inputs.values();
        for (var input = inputs.next(); input && !input.done; input = inputs.next()) {
            input.value.onmidimessage = midiOnMIDImessage;
        }
    }
navigator.requestMIDIAccess().then(requestMIDIAccessSuccess, requestMIDIAccessFailure);

请参见Working example