1

我正在尝试按照此处的指南在我的应用程序中实现 WebMIDI.js 库。

我已将 webmidi.min.js 文件添加到我的 index.html 页面,如下所示:

<script src="script.js"></script>
<script src="webmidi.min.js"></script>

我的 script.js 文件如下所示:

if (navigator.requestMIDIAccess) {
    console.log('This browser supports WebMIDI!');
} else {
    console.log('WebMIDI is not supported in this browser.');
}

navigator.requestMIDIAccess().then(onMIDISuccess, onMIDIFailure);

function onMIDIFailure() {
    console.log('Could not access your MIDI devices.');
}

function onMIDISuccess(midiAccess) {
    for (var input of midiAccess.inputs.values()){
        input.onmidimessage = getMIDIMessage;
    }
}

function getMIDIMessage(message) {
    var command = message.data[0];
    var note = message.data[1];
    var velocity = (message.data.length > 2) ? message.data[2] : 0; // a velocity value might not be included with a noteOff command

    switch (command) {
        case 144: // noteOn
            if (velocity > 0) {
                noteOn(note, velocity);
                console.log("Note pressed: " + note + " at " + velocity + " velocity");
            } else {
                noteOff(note);
                console.log("Note stopped");
            }
            break;
        case 128: // noteOff
            noteOff(note);
            break;
        // we could easily expand this switch statement to cover other types of commands such as controllers or sysex
    }
}

function noteOn(note){
}

function noteOff(note){
}

WebMidi.enable(function(err) {
   if (err) console.log("An error occurred", err);
   WebMidi.outputs[0].playNote("C3");
 });

但是,控制台会抛出有关未引用 WebMidi 的错误。

'script.js:47 Uncaught ReferenceError: WebMidi is not defined'

据我所知,我已经在我的 html 页面中包含了正确的 .js 文件,并且在那里引用了 WebMidi。我已经尝试将脚本标签添加到 webmidi.min.js 的在线版本,即 <script src="https://cdn.jsdelivr.net/npm/webmidi@2.0.0"></script>,但无济于事。我确定这是一个足够简单的问题,但我似乎无法弄清楚。任何帮助表示赞赏。

4

1 回答 1

0

您的 script.js 在加载 WEBMIDI.js 之前正在运行。尝试颠倒脚本标签的顺序。

<script src="webmidi.min.js"></script>
<script src="script.js"></script>
于 2020-02-03T16:39:14.427 回答