spessasynth_lib documentation
    Preparing search index...

    Class WorkerSynthesizer

    This synthesizer uses a Worker communicating with an AudioWorklet to provide real-time playback along with methods to export the data in various formats.

    Hierarchy (View Summary)

    Index
    • Creates a new instance of a Worker-based synthesizer.

      Parameters

      • context: AudioContext

        The audio context for the synthesizer to use.

      • workerPostMessage: {
            (message: any, transfer: Transferable[]): void;
            (message: any, options?: StructuredSerializeOptions): void;
        }

        The postMessage function of the Worker that the synthesizer will use. The raw Worker.postMessage can be passed here. This can be used for intercepting messages.

          • (message: any, transfer: Transferable[]): void
          • The postMessage() method of the Worker interface sends a message to the worker. The first parameter is the data to send to the worker. The data may be any JavaScript object that can be handled by the structured clone algorithm.

            MDN Reference

            Parameters

            • message: any
            • transfer: Transferable[]

            Returns void

          • (message: any, options?: StructuredSerializeOptions): void
          • Parameters

            • message: any
            • Optionaloptions: StructuredSerializeOptions

            Returns void

      • config: Partial<SynthConfig> = DEFAULT_SYNTH_CONFIG

        Optional configuration for the synthesizer.

      Returns WorkerSynthesizer

      Below is a simple example of creating a new synthesizer. Note that the two snippets are two files, one for the worker and one in the main thread.

      // Worker
      let workerSynthCore;
      // Wait for the first message with parameters
      onmessage = (e) => {
      if (e.ports[0]) {
      // Initialize
      workerSynthCore = new WorkerSynthesizerCore(
      e.data,
      e.ports[0],
      postMessage.bind(globalThis)
      );
      } else {
      // Handle all other messages
      void workerSynthCore.handleMessage(e.data);
      }
      };
      // Main thread
      // Create the audio context
      const context = new AudioContext({
      sampleRate: 44100
      });
      // Register the worklet
      await WorkerSynthesizer.registerPlaybackWorklet(context);
      // Create the worker
      const worker = new Worker(
      // Make sure that your path is correct
      new URL("worker.js", import.meta.url)
      );
      // Create the synthesizer and bind it to the worker
      const synth = new WorkerSynthesizer(context, worker.postMessage.bind(worker));
      worker.onmessage = (e) => synth.handleWorkerMessage(e.data);
    context: BaseAudioContext

    Synthesizer's parent audio context instance.

    convolverNode: ConvolverNode | undefined

    The AudioNode that processes the synthesizer's captured reverb tail through a Web Audio ConvolverNode.

    eventHandler: SynthEventHandler = ...

    The synthesizer's event handler. It allows setting up custom event listeners for the synthesizer.

    isReady: Promise<unknown>

    A promise that gets resolved when the synthesizer gets fully initialized.

    midiChannels: LibMIDIChannel[] = []

    The synthesizer's (virtual) MIDI channels.

    presetList: MIDIPatchFull[] = []

    The current preset list of the synthesizer, including all sound banks with their offsets set through the SoundBankManager.

    soundBankManager: SoundBankManager = ...

    The synthesizer's sound bank manager. It allows managing the sound bank list.

    • get currentTime(): number

      Returns the adjusted time, in sync with the worker's internal time which may differ from the AudioContext time.

      Returns number

    • get midiParameters(): Readonly<GlobalMIDIParameter>

      The GlobalMIDIParameters of the synthesizer. These are only editable via MIDI messages.

      Returns Readonly<GlobalMIDIParameter>

    • get systemParameters(): Readonly<GlobalSystemParameter>

      The GlobalSystemParameters of the synthesizer. These are only editable via the API.

      Returns Readonly<GlobalSystemParameter>

    • Apply pressure to the given channel. It usually controls the vibrato amount.

      Parameters

      • channel: number

        The MIDI channel to use. It usually ranges from 0 to 15, but it depends on the channel count.

      • pressure: number

        The pressure to apply. Ranges from 0 to 127. 0 means no pressure, 127 means max.

      • eventOptions: SynthMethodOptions = DEFAULT_SYNTH_METHOD_OPTIONS

        Additional options for this command.

      Returns void

      // Set channel 1 pressure to 64 (middle)
      synth.channelPressure(1, 64);
    • Connects a given channel output to the given audio node. Note that this output is only meant for visualization and may be silent when an insertion effect for this channel is enabled.

      Parameters

      • targetNode: AudioNode

        The node to connect to.

      • channelNumber: number

        The channel number to connect to, will be rolled over if value is greater than 15.

      Returns AudioNode

      The target node.

      // Create an analyzer for channel 1
      const analyzer = context.createAnalyser();
      synth.connectChannel(analyzer, 0);
    • Set a given MIDI controller to a given value.

      Parameters

      • channel: number

        The MIDI channel to use. It usually ranges from 0 to 15, but it depends on the channel count.

      • controller: MIDIController

        The MIDI CC number of the controller to change.

      • value: number

        The value to set the given controller to. Ranges from 0 to 127.

      • eventOptions: SynthMethodOptions = DEFAULT_SYNTH_METHOD_OPTIONS

        Additional options for this command.

      Returns void

      // Set controller 10 (Channel Pan) on channel 2 to 127 (hard right)
      synth.controllerChange(2, 10, 127);
    • Properly disposes of the synthesizer along with its audio nodes and the core. All pending operations (such as loading a sound bank) are rejected.

      Returns void

    • Disconnects a given channel output from the given audio node.

      Parameters

      • targetNode: AudioNode

        The node to disconnect from.

      • channelNumber: number

        The channel number to disconnect, will be rolled over if value is greater than 15.

      Returns void

      // Disconnect the analyzer from earlier
      synth.disconnectChannel(analyzer, 0);
    • Locks or unlocks a given GlobalMIDIParameter. This prevents any changes to it until it's unlocked.

      Type Parameters

      • P extends keyof GlobalMIDIParameter

      Parameters

      • parameter: P

        The Global MIDI Parameter to lock.

      • isLocked: boolean

        If the parameter should be locked.

      Returns void

      // Lock the MIDI system to GS
      synth.lockMIDIParameter("system", "gs");
    • Stops playing a note.

      Parameters

      • channel: number

        The MIDI channel to use. It usually ranges from 0 to 15, but it depends on the channel count.

      • midiNote: number

        The MIDI note number to stop. Ranges from 0 to 127.

      • eventOptions: SynthMethodOptions = DEFAULT_SYNTH_METHOD_OPTIONS

        Additional options for this command.

      Returns void

      // Stop the note 77 (F) on channel 15
      synth.noteOff(15, 77);
    • Starts playing a note.

      Parameters

      • channel: number

        The MIDI channel to use. It usually ranges from 0 to 15, but it depends on the channel count.

      • midiNote: number

        The MIDI note number to play. Ranges from 0 to 127.

      • velocity: number

        Controls how loud the note is. Ranges from 0 to 127, where 127 is the loudest and 1 is the quietest.

      • eventOptions: SynthMethodOptions = DEFAULT_SYNTH_METHOD_OPTIONS

        Additional options for this command.

      Returns void

      // Start the note 64 (E) on channel 0 with velocity of 120
      synth.noteOn(0, 64, 120);
    • Change the channel's pitch, including the currently playing notes.

      Parameters

      • channel: number

        The MIDI channel to use. It usually ranges from 0 to 15, but it depends on the channel count.

      • value: number

        The 14-bit pitch value. Ranges from 0 to 16383 where 8192 is no pitch change.

      • eventOptions: SynthMethodOptions = DEFAULT_SYNTH_METHOD_OPTIONS

        Additional options for this command.

      Returns void

      // Set pitch bend on channel 1 to middle (no change)
      synth.pitchWheel(1, 8192);
    • Change the channel's pitch bend range in semitones. It uses Registered Parameter Number controllers internally.

      Parameters

      • channel: number

        The MIDI channel to use. It usually ranges from 0 to 15, but it depends on the channel count.

      • range: number

        The bend range in semitones.

      • eventOptions: SynthMethodOptions = DEFAULT_SYNTH_METHOD_OPTIONS

        Additional options for this command.

      Returns void

      // Set the pitch bend range on channel 0 to +-12 semitones (one octave)
      synth.pitchWheelRange(0, 12);
    • Apply pressure to the given note on a given channel. It may be bound to specific parameters with system exclusive messages to allow for extra controls, such as per-note pitch wheel.

      Parameters

      • channel: number

        The MIDI channel to use. It usually ranges from 0 to 15, but it depends on the channel count.

      • midiNote: number

        The MIDI note number to apply pressure to. Ranges from 0 to 127.

      • pressure: number

        The pressure to apply. Ranges from 0 to 127.

      • eventOptions: SynthMethodOptions = DEFAULT_SYNTH_METHOD_OPTIONS

        Additional options for this command.

      Returns void

      // Set channel 11 pressure on note 60 (C) to 127 (max)
      synth.polyPressure(11, 60, 127);
    • Changes the program for the given channel.

      Parameters

      • channel: number

        The MIDI channel to use. It usually ranges from 0 to 15, but it depends on the channel count.

      • programNumber: number

        The MIDI program number to use. Ranges from 0 to 127.

      • eventOptions: SynthMethodOptions = DEFAULT_SYNTH_METHOD_OPTIONS

        Additional options for this command.

      Returns void

      // Change the program on channel 0 to 16 (drawbar organ)
      synth.programChange(0, 16);
    • Renders the current song in the connected sequencer to a single stereo AudioBuffer. This pauses the playback if it is playing.

      Parameters

      • sampleRate: number

        The sample rate to use, in Hertz.

      • renderOptions: RenderAudioOptions = DEFAULT_WORKER_RENDER_AUDIO_OPTIONS

        Options for rendering the audio data.

      Returns Promise<AudioBuffer>

      The complete stereo output, including the effects and convolver.

    • Renders the current song in the connected sequencer to the complete stereo output plus separate channel buffers. This pauses the playback if it is playing.

      Parameters

      • sampleRate: number

        The sample rate to use, in Hertz.

      • renderOptions: RenderAudioOptions = DEFAULT_WORKER_RENDER_AUDIO_OPTIONS

        Options for rendering the audio data.

      Returns Promise<RenderAudioResult>

      The complete stereo output and the separate visualization channels.

    • Sends a raw MIDI message to the synthesizer.

      Parameters

      • message: Iterable<number>

        The MIDI message to process.

      • channelOffset: number = 0

        Adds to the channel number of the message. It defaults to 0.

      • eventOptions: SynthMethodOptions = DEFAULT_SYNTH_METHOD_OPTIONS

        Additional options for this command.

      Returns void

      // Send a MIDI note on message for channel 2 with note 61 (C#) and velocity 120
      synth.sendMessage([0x92, 0x3d, 0x78]);
    • Sets spessasynth_core's log level in the processor.

      Parameters

      • enableInfo: boolean

        Enable info (verbose)

      • enableWarning: boolean

        Enable warnings (unrecognized messages)

      • enableGroup: boolean

        Enable groups (to group a lot of logs)

      Returns void

      // Enable all logs
      synth.setLogLevel(true, true, true);
    • Sets a GlobalSystemParameter to a given value.

      Type Parameters

      • K extends keyof GlobalSystemParameter

      Parameters

      • parameter: K

        The parameter to set.

      • value: GlobalSystemParameter[K]

        The value to set.

      Returns void

      // Set the master gain to 200%
      synth.setSystemParameter("gain", 2);
    • Sends a MIDI Sysex message to the synthesizer.

      Parameters

      • messageData: number[] | Iterable<number, any, any> | Uint8Array<ArrayBufferLike>

        The message's data, excluding the F0 byte, but including the F7 at the end.

      • channelOffset: number = 0

        The channel offset for the message as they usually can only address the first 16 channels. For example, to send a system exclusive on channel 16 (0-based), send a system exclusive for channel 0 and specify the channel offset to be 16.

      • eventOptions: SynthMethodOptions = DEFAULT_SYNTH_METHOD_OPTIONS

        Additional options for this command.

      Returns void

      // Send a GS DT1 Use Drums On Channel 10 (turn channel 10 into a drum channel)
      synth.systemExclusive([
      0x41, 0x10, 0x42, 0x12, 0x40, 0x1a, 0x15, 0x01, 0x10, 0xf7
      ]);

      // Send the same message with a channel offset of 10 (turn channel 20 into a drum channel)
      synth.systemExclusive(
      [0x41, 0x10, 0x42, 0x12, 0x40, 0x1a, 0x15, 0x01, 0x10, 0xf7],
      10
      );
    • Tunes individual MIDI key numbers on a given program using the MIDI Tuning Standard. Think of it as a pitch wheel but for individual notes.

      Parameters

      • program: number

        The MIDI program to tune. Ranges from 0 to 127.

      • tunings: { sourceKey: number; targetPitch: number }[]

        An array of tunings, each containing two properties:

        • sourceKey - The MIDI note number to tune.
        • targetPitch - The MIDI note number of the target pitch. Fractional values are allowed, for example, 60.5 is C plus 50 cents. A targetPitch of -1 restores the default tuning.

      Returns void

    • Registers an audio worklet for the WorkerSynthesizer.

      Parameters

      • context: BaseAudioContext

        The context to register the worklet for.

      • maxQueueSize: number = 20

        The maximum number of 128-sample chunks to store in the worklet. Higher values result in fewer dropouts but higher latency.

      Returns Promise<void>