Arrays / loops with midi.js

422 views Asked by At

I am looking to use a playsound function in midi.js to loop an array, with chords that i select, maybe 4 diff ones. But i can't figure it out. I can get it to do a single array, but not multiple, and it does not loop, only plays the amount of time I set it to (now 8).

window.onload = function () {
MIDI.loadPlugin({
    soundfontUrl: "../MIDI.js/examples/soundfont/",
    instrument: "acoustic_grand_piano",
    onprogress: function(state, progress) {
        console.log(state, progress);
    },


    onsuccess: function () {
               for (var i = 0; i < 9; i++){

               playsound([37,59,61,71,80])}

}});

var delay =1;   
function playsound($chords)
{
        var velocity = 127;
        MIDI.setVolume(0, 127);
        MIDI.chordOn(0, $chords, velocity, delay);
        MIDI.chordOff(0, $chords, delay+1);
        delay += 1;

}
1

There are 1 answers

0
Kai Carver On

Your code should work, except that for the timing to work predictably, I found you have to wait a bit after the success callback is called. If you call right after load, notes are played irregularly and out of sequence.

I recommend using a function like playChords below and testing well after load by calling the function with a button press. For example, this function plays three different chords at 1/2 second intervals, a total of 9 times.

chords = [[37,59,61,71,80],[38,60,62,72,81],[39,61,63,73,82]];
function playChords() {
  for (var i = 0; i < 9; i++){
    playChord(i/2, chords[i%chords.length]);
  } 
}
function playChord(delay, chord) {
  MIDI.chordOn(0, chord, 127, delay);
  MIDI.chordOff(0, chord, delay+1);
}