Skip to content

JavaScript/TypeScript ピッチとノート API ​

libsonare JavaScript/TypeScript パッケージのピッチ追跡とノート単位の解析の関数です。リクエストオブジェクトの規約は 特徴抽出 と同じです。

ピッチ検出 中負荷 ​

背景は メロディとピッチ を参照してください。

typescript
function pitchYin(request: PitchYinRequest): PitchResult
function pitchYin(
  samples: Float32Array,
  sampleRate: number,
  options?: OptionsOf<PitchYinRequest>,
): PitchResult

function pitchPyin(request: PitchPyinRequest): PitchResult
function pitchPyin(
  samples: Float32Array,
  sampleRate: number,
  options?: OptionsOf<PitchPyinRequest>,
): PitchResult

interface PitchYinRequest {
  samples: Float32Array;  // Mono audio samples.
  sampleRate: number;  // Sample rate of `samples` in Hz.
  frameLength?: number;  // Frame length in samples. Default 2048.
  hopLength?: number;  // Hop in samples. Default 512.
  f0MinHz?: number;  // Lowest pitch searched, in Hz. Default 65.
  f0MaxHz?: number;  // Highest pitch searched, in Hz. Default 2093.
  threshold?: number;  // YIN threshold. Default 0.1.
}

interface PitchPyinRequest {
  samples: Float32Array;  // Mono audio samples.
  sampleRate: number;  // Sample rate of `samples` in Hz.
  frameLength?: number;  // Frame length in samples. Default 2048.
  hopLength?: number;  // Hop in samples. Default 512.
  f0MinHz?: number;  // Lowest pitch searched, in Hz. Default 65.
  f0MaxHz?: number;  // Highest pitch searched, in Hz. Default 2093.
  threshold?: number;  // YIN threshold. Default 0.1.
  fillNa?: boolean;  // Return 0 for unvoiced f0 frames instead of NaN. Default `false`.
}

interface PitchResult {
  f0: Float32Array;  // Per-frame fundamental frequency in Hz; unvoiced frames are NaN.
  // pYIN's per-frame voiced **observation mass**, exactly as librosa returns it: the summed probability of the frame's voiced pitch hypotheses.
  //
  // This is NOT a signal-quality confidence and NOT a correction weight. The mass depends on how many periods of the pitch fit inside `frameLength`, because the CMNDF troughs of a long period measured over a short frame are shallower. For a fixed `frameLength` it therefore rises with F0 even when the signal is unchanged: a steady three-harmonic tone at 2048 samples / 48 kHz averages well under 0.1 at C2 and about 0.5 at C5, with every frame flagged voiced throughout.
  //
  // Use voicedFlag for any voicing decision. In particular, thresholding this value at a fixed 0.5 (`noteSegments`' default) drops entire low registers.
  voicedProb: Float32Array;
  voicedFlag: boolean[];  // Per-frame voicing decision from the Viterbi path — the voicing oracle.
  medianF0?: number;  // Median F0 in Hz over the voiced frames. Absent when no frame is voiced.
  meanF0?: number;  // Mean F0 in Hz over the voiced frames. Absent when no frame is voiced.
}

YIN は、voicedFlag が無声音と示すフレームも含め、すべてのフレームで有限の推定値を返します。

pYIN は既定では無声音の NaN を保持します。後段で 0 が必要な場合だけ fillNa: true を指定してください。

ノートと打撃音 ​

この 4 つは解析と編集の中間にあります。いずれも音声が明示していないものを測り、ホストが編集してレンダリングできるオブジェクトを返します。周辺の編集ワークフローは ノート編集 にまとめています。

analyzePolyphonic(request) 高負荷 ​

typescript
function analyzePolyphonic(request: AnalyzePolyphonicRequest): PolyphonicAnalysis
function analyzePolyphonic(
  samples: Float32Array,
  sampleRate: number,
  options?: OptionsOf<AnalyzePolyphonicRequest>,
): PolyphonicAnalysis

interface AnalyzePolyphonicRequest extends PolyphonicAnalysisOptions {
  samples: Float32Array;  // Source audio; must be non-empty.
  sampleRate: number;  // Sample rate in Hz. Required: every duration in the chain — the ridge minimum, the note minimum, the per-frame windows — is converted to samples with this rate, so a wrong value silently analyses differently.
}

和音を構成するノートを分離し、そのうち 1 つだけを編集して他はそのまま残せるようにします。返るのは結果オブジェクトではなくハンドルです。解析は音源の複素スペクトログラムと各ノートが取得したビンを保持しており、これは入力そのものに取得情報を足したものに相当します。これを保持しているため、編集後の再レンダリングに追加のコストがかかりません。

用が済んだらすぐに destroy() してください。解放後に使うと、解放済みオブジェクトに触れるのではなく InvalidState が送出されます。JavaScript 側へ渡るのはホストが実際に扱うものだけです。ノート一覧、各ノートの保留中の編集、フレームごとの発音数、そしてノートごとのピッチ・レベル・サリエンス曲線。スペクトログラム、マスク、ビンごとの重みは渡りませんし、ビン単位の数値を報告するメソッドもありません。

sampleRate は既定値を持たず必須です。処理系の全ての時間量がこの値でサンプル数へ変換されるため、誤った値を渡すと失敗せずに違う解析をします。

decomposeNotePitch(request) ​

typescript
function decomposeNotePitch(request: DecomposeNotePitchRequest): PitchDecompositionResult

interface DecomposeNotePitchRequest {
  f0Hz: Float32Array;  // The note's slice of the F0 track — `f0Hz.subarray(frameStart, frameEnd)`. Positive finite values carry pitch; other values carry no measurement.
  voiced?: VoicedFlags;  // Per-frame voiced flags matching `f0Hz`; false suppresses a candidate and true cannot make an unusable F0 valid.
  frameRate: number;  // F0 frames per second.
  medianHz: number;  // The note's `medianHz`. A note with no pitch is spelled 0, so a negative value is rejected rather than read as a second way of saying that.
  vibratoCutoffHz?: number;  // Where drift ends and vibrato begins, in Hz. Default 3 Hz.
}

interface PitchDecompositionResult {
  centerHz: number;  // The note's steady pitch in Hz. 0 when the note carries no usable pitch, and then both curves are empty.
  driftCents: Float32Array;  // Slow deviation from `centerHz` in cents, one entry per frame.
  vibratoCents: Float32Array;  // Fast deviation in cents, over the same frames.
}

1 つのノートのピッチ曲線を、そこに同時に含まれる 3 つの成分へ分けます。狙った中心音、その周りのゆっくりした揺れ、そしてその上に乗る周期的な振動です。どれか 1 つを編集するには、まず分離する必要があります。

ドリフトとビブラートの境界を決めているのは vibratoCutoffHz だけです。同じカットオフを renderNotes にも渡してください。 そうしないと、ユーザーに表示しているものとは別の曲線を編集することになります。

元の f0Hz トラックを Float32Array で渡し、任意で同じ長さの voiced フラグ配列も渡します。false は F0 が正でもそのフレームを抑制し、true でも 0 以下・有限でない・その他の理由で利用できない F0 は有効になりません。f0Hz と一緒に frameRate と medianHz(そのノートの medianHz。ピッチのないノートは 0)も必要です。カーブ編集をレンダーするときは同じトラック、フラグ、フレームレート、カットオフを使います。通常のノート編集に F0 メタデータは不要です。

F0 が使えないフレームには測定値がないため、曲線は最も近い有効な隣接値で保持されます。したがってどちらの曲線も全フレームに値を持ちます。保持された箇所を示したいホストは、f0Hz と、渡している場合は voiced フラグを合わせて確認できます。使えるピッチが全く無いノートは、エラーではなく centerHz が 0 で 2 本の曲線が空という形で返ります。これは引数の誤りではなく、測定が空振りしたという報告です。

extractPercussiveEvents(request) と renderPercussiveEvents(request) ​

typescript
function extractPercussiveEvents(request: ExtractPercussiveEventsRequest): PercussiveEvent[]
function extractPercussiveEvents(
  samples: Float32Array | readonly number[],
  sampleRate: number,
  options?: OptionsOf<ExtractPercussiveEventsRequest>,
): PercussiveEvent[]

function renderPercussiveEvents(request: RenderPercussiveEventsRequest): Float32Array
function renderPercussiveEvents(
  samples: Float32Array | readonly number[],
  sampleRate: number,
  options: OptionsOf<RenderPercussiveEventsRequest>,
): Float32Array

interface ExtractPercussiveEventsRequest extends PercussiveSeparationOptions {
  samples: Float32Array | readonly number[];  // Source audio; a plain number array is copied to a `Float32Array` first.
  sampleRate: number;  // Sample rate in Hz. Required: `maxEventMs` is converted to samples with this rate, so a wrong/omitted value caps the spans differently.
  onsetWait?: number;  // Minimum frames between consecutive onsets, a positive whole number. Default 1; an explicit 0 or a negative wait is refused, and a fractional wait is refused rather than truncated.
  onsetDelta?: number;  // Offset added to the detector's adaptive threshold; raising it finds fewer, stronger hits and lowering it finds more. Default 0.06. An explicit 0 is refused because the native configuration would read it as the default; a negative one is accepted and puts the threshold below the default.
  maxEventMs?: number;  // Caps a span that no onset follows. It binds at the end of a phrase and at the end of the track; anywhere else the next onset closes the span first. Default 500 ms; an explicit 0 is refused.
  minPercussiveRatio?: number;  // Drops an event whose `percussiveRatio` falls below this; must be in `[0, 1]`. 0 is both the default and the meaningful "keep everything". Raising it is useful on material that is mostly drums and wrong on a dense mix, where it also drops real hits sitting over a loud sustain.
}

interface RenderPercussiveEventsRequest extends PercussiveSeparationOptions {
  samples: Float32Array | readonly number[];  // Source audio; a plain number array is copied to a `Float32Array` first.
  sampleRate: number;  // Sample rate in Hz. Required: `fadeMs` is converted to samples with this rate, so a wrong/omitted value changes the fade length.
  events: readonly PercussiveEventInput[];  // The events to render, with their edits. Source spans must not overlap.
  fadeMs?: number;  // Fade-out at the tail of each lifted span. Default 5 ms; an explicit 0 is refused rather than read as that default — and a hard cut is not a thing to want anyway, because what the fade shapes is the signal being subtracted, so squaring it off leaves a step. There is deliberately no matching fade-in: a span opens in front of its transient, where the percussive component is near-silent, so cutting square there costs nothing and keeps a muted hit's attack from surviving inside a fade.
}

interface PercussiveSeparationOptions {
  nFft?: number;  // FFT size and hop the separation and the onset detector share. They cannot be set apart: an event measured on one framing and lifted out on another is not the same signal. Default 2048 and a quarter of `nFft`. The pair must overlap-add — `nFft` even and at least 2, `hopLength` no more than half of it — because the separation inverts an STFT. An explicit 0 in any separation field is refused; leave the field out for its default.
  hopLength?: number;  // Hop length in samples. Default a quarter of `nFft`.
  hpssKernelHarmonic?: number;  // Median filter lengths the separation runs, along time and along frequency. A longer harmonic kernel calls more of a sustained sound harmonic. Default 31; any other value must be odd and positive, so an even one is rejected rather than rounded. 1 is legal and degenerate rather than an error: a length-1 median is the identity, so both components come back as the source.
  hpssKernelPercussive?: number;  // Vertical median filter length, under the same rule. Default 31.
}

interface PercussiveEventInput {
  onsetSample?: number;  // First sample of the span. Give this or `onsetSec`.
  onsetSec?: number;  // First second of the span, rounded to the nearest sample. Not with `onsetSample`.
  offsetSample?: number;  // One past the last sample of the span. Give this or `offsetSec`.
  offsetSec?: number;  // End of the span in seconds, rounded to the nearest sample. Not with `offsetSample`.
  edit?: PercussiveEventEditInput;  // Omit for the identity edit.
}

interface PercussiveEvent {
  onsetSample: number;  // First sample of the span, backtracked to in front of the transient.
  offsetSample: number;  // One past the last sample of the span; the next onset, or the cap.
  strength: number;  // Detector strength at the onset, on the onset envelope's own scale. It orders events against each other and carries no absolute meaning.
  peakAmplitude: number;  // Peak absolute sample of the percussive component over the span, linear. Measured on the signal `gainDb` scales rather than on the source.
  // Share of the span's energy the separation assigned to percussion, in `[0, 1]`; absent when the span is silent.
  //
  // It describes the span rather than the onset that opened it. An isolated hit sits near 1, but a real hit over a loud sustain sits near 0, because the sustain owns the span's energy. So it separates a hit from a note attack only where nothing is sustaining through both, and it is not a test for whether a hit is there.
  percussiveRatio?: number;
  edit: PercussiveEventEdit;  // This event's pending edit; the identity as returned.
}

対で使います。前者は音声だけから打撃音を検出します。各イベントは、ソースのサンプル位置で表した区間、検出器の強度、区間内の打撃成分のピーク、区間のエネルギーのうち分離が打撃成分と判定した割合、そして恒等変換の編集内容を持ちます。イベントを編集して後者へ渡すと、音声が返ります。ソースは決して書き換わりません。全ての編集が恒等変換のままなら、レンダリング結果は入力と一致します。

両者は同じ分離オプションを取り、どちらも sampleRate を必要とします。理由も同じで、maxEventMs と fadeMs をサンプル数へ変換するためです。

既定値のうち 2 つは押さえておいてください。minPercussiveRatio の既定は 0、つまり「すべて残す」です。上げるとドラム主体の素材では役に立ちますが、密度の高いミックスでは逆効果で、大きな持続音に重なった本物の打撃音まで落とします。fadeMs の既定は 5 ms で、このフェードが掛かるのは減算される側の信号です。そのため「切り落とし」を指定する手段はありません。角を立てると段差が残るからです。対応するフェードインは意図的にありません。区間はトランジェントの手前で始まり、そこでは打撃成分がほぼ無音だからです。

分離のメディアンカーネル長は奇数かつ正である必要があります。偶数は丸めずに拒否されます。1 は正当ですが退化した指定で、長さ 1 のメディアンは恒等写像なので、両方の成分がソースそのままで返ります。