Skip to content

JavaScript/TypeScript 楽器と MIDI API ​

内蔵シンセサイザーのカタログ、ホストが用意する SampleBank、SoundFont 再生、そしてライブ MIDI とマイク音声をエンジンへ流すブラウザ向けヘルパーです。これらを載せるクラスは プロジェクト と リアルタイムエンジン にあります。

タスク別の参照先 ​

目的使う APIガイド
内蔵シンセサイザー(NativeSynth)のボイスを選ぶsynthPresetNames()、synthPresetPatch(name)、engine.setSynthInstrument(...)内蔵シンセサイザー
SoundFont で再生project.loadSoundFont(bytes, { uri }) / engine.loadSoundFont(bytes)SoundFont プレイヤー
ハードウェア/Web MIDI デバイスからエンジンへ演奏イベントを送るbindWebMidi(engine, ...) ブラウザ専用MIDI 入力
ライブのマイク入力をエンジンに流すbindMicrophoneInput(context, engine, ...) ブラウザ専用録音とテイク

bindWebMidi(...) と bindMicrophoneInput(...) はブラウザ専用のヘルパーで、Web MIDI や MediaStream をライブの RealtimeEngine に接続します。

ライフサイクル ​

Project は既定の SoundFont と複数の名前付き SoundFont を保持できます。loadSoundFont、clearSoundFont、soundFontPresetCount、soundFontManifest は任意の { uri } を受け取ります。uri を省略すると既定を選びます。SF2 バウンスバインディングの soundFontUri で、そのレンダーに使う名前付き音源を選べます。省略すると既定を使います。RealtimeEngine.loadSoundFont(bytes) はエンジン専用の 1 つの SoundFont スロットを使います。プロジェクトへの不正な読み込みは例外になり、選択したスロットにあった音源を保持します。SampleBank は WASM ヒープのオブジェクトです。コントロールスレッドで組み立てます。サンプルとゾーンは、それをバインドするバウンスが始まる前にすべて追加し、名指ししたバウンスがすべて終わってから destroy() します(冪等で、using も使えます)。bindWebMidi と bindMicrophoneInput は、destroy() で接続を解除するバインディングを返し、こちらも using が使えます。ここにあるものでリアルタイム安全なのは、次に処理されるブロックの先頭からのオフセットでイベントを受け取るエンジン自身の MIDI 入力キューだけです。未知のプリセット名や不正なパッチは RangeError です。詳細は エラー規約 を参照してください。

内蔵シンセのカタログ ​

typescript
function synthPresetNames(): string[]

function synthPresetPatch(name: string): SynthPatch

function synthEngineParamInfo(engineMode: SynthEngineMode): SynthParamInfo[]

function synthPatchParamInfo(): SynthPatchParamInfo[]

function synthEnumTables(): SynthEnumTables

function synthGsDrumKitName(program: number): string | null

function synthGsDrumKitIsVoicedApart(program: number): boolean | null

function synthGsVariationIsVoicedApart(bank: number, program: number): boolean | null

SampleBank ​

typescript
class SampleBank {
  readonly nativeId: number;  // Identity a binding names this bank by, so no raw pointer crosses into JS. Hosts pass the `SampleBank` itself as `sampleBank`.
  constructor();  // Create an empty bank.
  // Copy mono float frames into the bank and return the new sample's index, which SampleZoneDesc.sampleIndex names. The frames are copied, so the array may be reused afterwards.
  //
  // Loop points are clamped inside the sample and a loop mode whose loop survives the clamp empty is dropped, so a malformed loop plays as an unlooped sample rather than as a wrap over nothing. An empty array, and a bank that would exceed 67,108,864 sample points, throw.
  //
  // A NaN or Inf frame, `fineTuneCents` or `sourceRate` throws too, and the bank is left unchanged. Such a value is unattributable once stored: the reader's interpolation spreads one bad frame across the whole sustain, and a bad tuning offset renders the voice silent with no error raised.
  addSample(data: Float32Array, desc?: SampleDesc): number;
  // Append a key/velocity rectangle to a keymap set, creating any sets below it. A patch names a set; the first zone in it covering a note is the one that sounds.
  //
  // Every bound defaults on its own (see SampleZoneDesc), so an empty rectangle is the whole keyboard at every velocity and narrowing one axis leaves the other whole. A `sampleIndex` the bank does not have, an inverted key or velocity range, and a `setIndex` at or above 4096 all throw.
  addZone(zone?: SampleZoneDesc): void;
  get sampleCount(): number;  // Samples added so far.
  get setCount(): number;  // Keymap sets the bank has (one past the highest index used).
  destroy(): void;  // Release the underlying WASM object. Idempotent, as the Node facade is.
  [Symbol.dispose](): void;  // Releases the handle through destroy, so the instance works with `using`.
}

ライブ MIDI とマイク入力 ​

typescript
function bindWebMidi(engine: WebMidiEngine, options?: BindWebMidiOptions): Promise<WebMidiBinding>

function isWebMidiAvailable(): boolean

interface BindWebMidiOptions {
  destinationId?: number;  // Realtime-engine MIDI destination receiving the live input source. Default `0`.
  group?: number;  // UMP group used for MIDI 1.0 channel voice events. Default `0`.
  inputIds?: readonly string[];  // Restrict binding to specific Web MIDI input ids. Omit or empty = all connected inputs.
  sysex?: boolean;  // Request SysEx-capable access from the browser. Default `false`.
  software?: boolean;  // Request software ports from the browser where supported. Default `true`.
  ccBindings?: readonly ProjectMidiCcBinding[];  // Bind CC-to-parameter mappings before ports are connected.
  timestampToOffsetInBlockSamples?: (eventTimeMs: number) => number;  // Convert a Web MIDI event timestamp to an offset in samples into the next block drained (clamped to its last frame, negative reads as 0). Return a block-relative offset, not the timestamp scaled to samples: an absolute value lands every event on one frame. Omit for offset 0. Exclusive with context.
  context?: WebMidiAudioContext;  // The AudioContext the engine renders in. Each event's timestamp is placed on its clock by webMidiEventContextTime, delayed by scheduleAheadSec, and pushed with `contextTimeSec`, so events keep their spacing to the sample instead of bunching at block heads. Requires an engine whose pushes take `contextTimeSec` (the AudioWorklet `SonareEngine`). Exclusive with timestampToOffsetInBlockSamples.
  scheduleAheadSec?: number;  // Seconds each event is delayed on the context clock in context mode. Default: the context's `baseLatency + outputLatency` (a missing or non-finite value reads as 0) plus two render quanta, read per event. A smaller value answers sooner and plays more events late, at the next block's start; a larger one keeps every event on its sample at the cost of that delay. `0` is allowed.
  onInputsChanged?: (inputs: WebMidiInputInfo[]) => void;  // Observe hot-plug updates after the helper rebinds matching inputs.
  filter?: (message: WebMidiMessage) => boolean;  // Called with each message the binding is about to push, before it reaches the engine; returning a falsy value drops that message (a MIDI-learn mode, for instance). System messages the binding never pushes are not offered.
}

interface WebMidiBinding {
  access: MidiAccessLike;  // The browser's MIDIAccess object.
  inputs(): WebMidiInputInfo[];  // Current snapshot of every input port, bound or not.
  destroy(): void;  // Stops listening on every bound input and for hot-plug changes, releases what each input still held, and clears the engine's MIDI input source; both last steps are skipped when a newer binding has replaced the source. Safe to call more than once.
  [Symbol.dispose](): void;  // Same as destroy, so the binding works with `using`.
}

function bindMicrophoneInput(
  context: AudioContext,
  engine: SonareRealtimeEngineNode | AudioWorkletNode,
  options?: BindMicrophoneInputOptions,
): Promise<MicrophoneInputBinding>