spessasynth_lib documentation
    Preparing search index...

    Simple MIDI Player Example

    See this demo live

    This example demonstrates how to quickly set up a synthesizer and a sequencer to play a MIDI file.

    The example uses two classes: WorkletSynthesizer and Sequencer to play a MIDI file.

    <p id="message">Please wait for the sound bank to load.</p>
    <input accept=".mid, .rmi, .xmf, .mxmf" id="midi_input" type="file" />
    <!-- note the type="module" -->
    <script src="simple_demo.js" type="module"></script>
    // Import the modules
    import { Sequencer, WorkletSynthesizer } from "../../src";
    import {
    EXAMPLE_SOUND_BANK_PATH,
    EXAMPLE_WORKLET_PATH
    } from "../examples_common";

    // Load the sound bank (your path may vary)
    const response = await fetch(EXAMPLE_SOUND_BANK_PATH);
    // Load the sound bank into an array buffer
    const sfFile = await response.arrayBuffer();
    document.querySelector("#message")!.textContent = "Sound bank has been loaded!";

    // Create an audioContext and add the worklet
    const context = new AudioContext();
    await context.audioWorklet.addModule(EXAMPLE_WORKLET_PATH);
    // Create the synthesizer
    const synth = new WorkletSynthesizer(context);
    synth.connect(context.destination);
    // Add the sound bank
    await synth.soundBankManager.addSoundBank(sfFile, "main");
    // Create the sequencer
    const seq = new Sequencer(synth);

    // Make it loop
    seq.loopCount = Infinity;

    // Add an event listener for the file input
    document
    .querySelector("#midi_input")!
    .addEventListener("change", async (event) => {
    // Audio context may only be resumed after user interaction
    await context.resume();
    const input = event.target as HTMLInputElement;
    // Check if any files are added
    const file = input.files?.[0];
    if (!file) {
    return;
    }
    const midiFile = await file.arrayBuffer(); // Get the file and convert to ArrayBuffer

    // Load a new song list and play
    seq.loadNewSongList([{ binary: midiFile }]);
    seq.play();
    });

    What the script does:

    1. Imports the necessary classes
    2. Fetches the sound bank file
    3. Initializes an AudioContext and adds the worklet
    4. Initializes a WorkletSynthesizer instance
    5. Adds the sound bank to the synthesizer
    6. Initializes a Sequencer instance and connects it to the WorkletSynthesizer
    7. Adds a listener for the file input:
      • Loads the selected MIDI file into the song list
      • Starts the playback via sequencer.play()

    It's that simple!