Skip to content

JavaScript/TypeScript エフェクト API ​

libsonare JavaScript/TypeScript パッケージのオーディオエフェクトと編集 DSP です。ルーム音響の関数は ルーム音響 API にあります。

オーディオエフェクト ​

hpss(samples, sampleRate, options?) 高負荷 ​

HPSS(Harmonic / Percussive Source Separation。倍音成分/打撃成分の分離)。音源を倍音成分(ボーカル、シンセなどの持続音)と打撃成分(ドラム、過渡音)に分離します。

HPSS · FULL MIXIDLE
HPSS — 旋律と打楽器を分ける

スペクトログラムでは、持続する倍音成分は横方向の筋、立ち上がりの鋭い打撃成分は縦方向の筋になりやすくなります。HPSS はメディアンフィルタとマスクで、この構造を分けます。フルミックス・倍音成分・打撃成分を切り替えて試聴してください。楽器を個別に分離する処理ではないため、音程を持つ音の立ち上がりが打撃成分に入り、長く響くシンバルが倍音成分に入ることもあります。

レイヤー

nFft は 4 以上の偶数で、混合基数 FFT のサイズも使えます。hopLength は (0, nFft / 2] の整数(既定 nFft / 4)、両方のメディアンカーネルは 524287 以下の正の奇数を指定します。内部の STFT 窓と winLength の組み合わせも、重ね合わせに隙間ができないことが必要です。JavaScript のヘルパーは既定の窓設定を使います。不正な設定は、周期的な音抜けを返す代わりに拒否します。

パフォーマンス

HPSS は STFT(短時間フーリエ変換)とメディアンフィルター処理を必要とします。処理時間は音源の長さに比例します。

typescript
function hpss(request: HpssRequest): HpssResult
function hpss(
  samples: Float32Array,
  sampleRate: number,
  options?: OptionsOf<HpssRequest>,
): HpssResult

interface HpssRequest {
  samples: Float32Array;  // Mono input audio.
  sampleRate: number;  // Sample rate in Hz, an integer in `[8000, 384000]`; there is no default.
  kernelHarmonic?: number;  // Horizontal median filter size, in STFT frames: a positive odd integer at most 524287. Default 31. The ceiling is 524288 and an even kernel is refused, so 524287 is the largest legal value.
  kernelPercussive?: number;  // Vertical median filter size, in STFT bins, under the same rule. Default 31.
  nFft?: number;  // FFT size in samples. Default 2048.
  hopLength?: number;  // Hop in samples. Default `nFft / 4`, rounded down.
  hardMask?: boolean;  // Threshold the masks into binary ones instead of the soft split. Default `false`.
  withResidual?: boolean;  // Also return `residual`, what neither component claimed. Default `false`.
}

interface HpssResult {
  harmonic: Float32Array;  // Harmonic component, the same length as the input.
  percussive: Float32Array;  // Percussive component, the same length as the input.
  residual?: Float32Array;  // What neither component claimed (input - harmonic - percussive), the same length as the input.
  sampleRate: number;  // Sample rate in Hz of both components.
}

withResidual: true を指定すると、hpss は倍音成分と打撃成分のどちらにも分類されなかった残差成分も返します。ほかのオプションは変わりません。

typescript
const result = hpss({ samples, sampleRate, withResidual: true }); // result.residual is present

harmonic(samples, sampleRate) 高負荷 ​

音源から倍音成分を抽出します。

typescript
function harmonic(request: HarmonicRequest): Float32Array
function harmonic(
  samples: Float32Array,
  sampleRate: number,
  options?: OptionsOf<HarmonicRequest>,
): Float32Array

percussive(samples, sampleRate) 高負荷 ​

音源から打撃成分を抽出します。

typescript
function percussive(request: PercussiveRequest): Float32Array
function percussive(
  samples: Float32Array,
  sampleRate: number,
  options?: OptionsOf<PercussiveRequest>,
): Float32Array

timeStretch(samples, sampleRate, options) 高負荷 ​

ピッチを変えずにテンポを変更します。speedRatio が 1.0 未満なら遅く、1.0 より大きければ速くなります。タイムストレッチとピッチシフト も参照してください。

PARAM SWEEP · TIME STRETCHIDLE
タイムストレッチ — 音程はそのまま、長さを変える

タイムストレッチは、音程をほぼ保ちながら長さを変えます。レートが 1 未満なら遅く長く、1 より大きければ速く短くなります。波形の幅で長さの変化を確認できます。各レンダーはピークを揃えていますが、知覚上の音量まで一致するわけではありません。タイミングと立ち上がりの明瞭さを聴き比べてください。

試聴対象
再生中に切り替えると、選んだ音を先頭から再生します。処理後
レート
1 ×

パフォーマンス

フェーズボコーダーを使います。処理時間はオーディオの長さに比例します。

typescript
function timeStretch(request: TimeStretchRequest): Float32Array
function timeStretch(
  samples: Float32Array,
  sampleRate: number,
  options: OptionsOf<TimeStretchRequest>,
): Float32Array

interface TimeStretchRequest {
  samples: Float32Array;  // Mono input audio.
  sampleRate: number;  // Sample rate in Hz. Required.
  speedRatio: number;  // Playback speed: `> 1` is faster and shorter (2 halves the duration), `< 1` is slower and longer (0.5 doubles it).
  nFft?: number;  // FFT size: an even integer in `[4, 2147483646]`. Default 2048.
  hopLength?: number;  // Hop in samples, in `(0, nFft / 2]`. Default `nFft / 4`, rounded down.
}

pitchShift(samples, sampleRate, options) 高負荷 ​

長さを変えずにピッチを変更します。単位は半音で、+12 が 1 オクターブ上です。タイムストレッチとピッチシフト も参照してください。

パフォーマンス

タイムストレッチとリサンプリングを組み合わせます。処理時間はオーディオの長さに比例します。

typescript
function pitchShift(request: PitchShiftRequest): Float32Array
function pitchShift(
  samples: Float32Array,
  sampleRate: number,
  options: OptionsOf<PitchShiftRequest>,
): Float32Array

interface PitchShiftRequest {
  samples: Float32Array;  // Mono input audio.
  sampleRate: number;  // Sample rate in Hz. Required.
  pitchSemitones: number;  // Shift in semitones: +12 is one octave up, -12 one octave down.
  nFft?: number;  // FFT size: an even integer in `[4, 2147483646]`. Default 2048.
  hopLength?: number;  // Hop in samples, in `(0, nFft / 2]`. Default `nFft / 4`, rounded down.
}

編集 DSP ​

これらの関数は解析ではなく、信号そのものを書き換えます。Audio インスタンスメソッドとしても利用でき、その場合は保持している sampleRate が自動的に使われます。背景は ピッチ補正とノート編集 と ボイスとフォルマント を参照してください。どれも 1 つのリクエストオブジェクトを受け取り、位置引数形式 (samples, sampleRate, options) がある関数にはそれも示しています。ブロックは WASM パッケージの型宣言から取っており、Node も同じフィールドを宣言しています。

typescript
function pitchCorrectToMidi(request: PitchCorrectToMidiRequest): Float32Array
function pitchCorrectToMidi(
  samples: Float32Array,
  sampleRate: number,
  options: OptionsOf<PitchCorrectToMidiRequest>,
): Float32Array

interface PitchCorrectToMidiRequest {
  samples: Float32Array;  // Mono input audio.
  sampleRate: number;  // Sample rate in Hz. Required.
  currentMidi: number;  // MIDI note the audio currently sits on, in `[0, 127]`.
  targetMidi: number;  // MIDI note to move it to, in `[0, 127]`.
}

function pitchCorrectTimevarying(request: PitchCorrectTimevaryingRequest): Float32Array
function pitchCorrectTimevarying(
  samples: Float32Array,
  sampleRate: number,
  options: PitchCorrectOptions,
): Float32Array

interface PitchCorrectTimevaryingRequest extends PitchCorrectOptions {
  samples: Float32Array;  // Mono input audio.
  sampleRate: number;  // Sample rate in Hz. Required.
}

interface PitchCorrectOptions {
  f0Hz: Float32Array;  // Per-frame measured F0 in Hz, one entry per analysis frame.
  hopLength?: number;  // F0 frame-center spacing in samples: frame `i` is centered at sample `i * hopLength`, and nearest-frame voicing switches halfway between centers. Default 512.
  targetMode?: PitchTargetMode;  // `'midi'` retunes toward `targetMidi`; `'scale'` snaps to the key. Default `'midi'`.
  targetMidi?: number;  // Fixed target note when `targetMode` is `'midi'`, in `[0, 127]`. Default 69 (A4).
  scaleRoot?: number;  // Scale root pitch class (0=C .. 11=B) when `targetMode` is `'scale'`. Default 0.
  scaleModeMask?: number | KeyMode;  // Scale degrees enabled: a 12-bit mask (bit `i` = semitone `i` above the root) or a mode name, as `scaleMaskForMode` resolves it. Default C major.
  scaleReferenceMidi?: number;  // Reference MIDI anchoring the scale grid. Default 69 (A4).
  retuneAmount?: number;  // Correction strength in `[0, 1]`; 1 = full snap, 0 = bypass. Default 1.
  maxCorrectionSemitones?: number;  // Hard clamp on per-frame correction magnitude (semitones). Default 12.
  retuneSpeedMs?: number;  // Retune IIR time constant (ms); larger = slower glide. Default 50.
  vibratoThresholdCents?: number;  // Corrections below this are bypassed to preserve vibrato (cents). Default 20.
  voiced?: VoicedFlags;  // Per-frame voiced flags (truthy = voiced); when supplied, these take precedence over `voicedProb`. Omit it to use `voicedProb`; with neither, all frames are treated as voiced.
  voicedProb?: Float32Array;  // Per-frame voicing probability in `[0, 1]`; used only when `voiced` is omitted, and ignored when flags are supplied.
}

type VoicedFlags =
  | Int32Array
  | Uint8Array
  | Float32Array
  | readonly number[]
  | readonly boolean[];

VoicedFlags は PitchCorrectOptions.voiced が受け付ける形です。解析側が返すものをそのまま扱えます。PitchResult.voicedFlag は boolean[] なので、ピッチトラックを変換なしでピッチ補正に渡せます。

typescript
const pitch = pitchPyin(samples, sampleRate);
const tuned = pitchCorrectTimevarying({
  samples,
  sampleRate,
  f0Hz: pitch.f0,
  hopLength: 512,
  targetMode: 'midi',
  targetMidi: 69,
  voiced: pitch.voicedFlag,   // boolean[] はそのまま渡せる
});

voiced は f0Hz と同じ長さである必要があります。voiced を省略する場合は voicedProb も f0Hz と同じ長さにします。長さが食い違うと RangeError(たとえば pitchCorrectTimevarying: voiced must have the same length as f0Hz)を投げます。SonareError ではないため isSonareError では捕捉できません。有声として扱うすべてのフレームの f0Hz は、有限で正の値であり、ナイキスト周波数(sampleRate / 2)以下である必要があります。これに違反すると呼び出しを拒否します。無声フレームでは NaN(または 0 以上ナイキスト周波数以下の有限値)を使えますが、有声フレームの NaN は無効です。

voicedProb が決めるのは有声判定だけ

voicedProb の用途は 1 つだけです。voiced を渡さなかったときに、フレームごとの有声/無声の判定を導くことです。voiced を渡した場合、voicedProb は完全に無視されます。両方渡しても voicedProb は使われないため、上の例ではフラグだけを渡しています。

特に、フレームごとの補正量をスケーリングすることはありません。確率で重み付けされた緩やかなリチューンを期待して voicedProb を渡していた場合、実際にはそうなっておらず、聞こえる補正はその想定より低音域で強くなります。voicedProb は F0 とともに上昇するため、その想定でもっとも減衰されていたはずのフレームが低音域だからです。補正を緩めるには retuneAmount と vibratoThresholdCents を使ってください。

typescript
function noteStretch(request: NoteStretchRequest): Float32Array
function noteStretch(
  samples: Float32Array,
  sampleRate: number,
  options: NoteStretchOptions,
): Float32Array
function noteMove(request: NoteMoveRequest): Float32Array
function noteMove(
  samples: Float32Array,
  sampleRate: number,
  options: NoteMoveOptions,
): Float32Array

interface NoteStretchOptions {
  onsetSample?: number;  // Note onset position in samples (selects the region). Default 0. Not with `onsetSec`.
  onsetSec?: number;  // Note onset in seconds, rounded to the nearest sample. Not with `onsetSample`.
  offsetSample?: number;  // Note offset position in samples (selects the region). Defaults to the input length. Not with `offsetSec`.
  offsetSec?: number;  // Note offset in seconds, rounded to the nearest sample. Not with `offsetSample`.
  stretchRatio: number;  // Duration ratio of the note (0.5 = half duration, 2.0 = double duration).
}

interface NoteMoveOptions {
  onsetSample?: number;  // First sample of the note to move. Default 0. Not with `onsetSec`.
  onsetSec?: number;  // First second of the note to move, rounded to the nearest sample. Not with `onsetSample`.
  offsetSample?: number;  // Defaults to the input length. Not with `offsetSec`.
  offsetSec?: number;  // Last second of the note to move, rounded to the nearest sample. Not with `offsetSample`.
  targetOnsetSample?: number;  // Sample the note's onset moves to. Required unless given as `targetOnsetSec`.
  targetOnsetSec?: number;  // Second the note's onset moves to, rounded to the nearest sample. Not with `targetOnsetSample`.
}

Audio.noteStretch(options) と Audio.noteMove(options) は Audio インスタンス上の対応メソッドです(サンプルレートはインスタンスの値を使います)。負のサンプル位置(onsetSample、offsetSample、targetOnsetSample)は、フィールド名を挙げた RangeError で拒否されます。各位置は秒でも指定でき(onsetSec、offsetSec、targetOnsetSec)、1 つの境界を両方の綴りで指定することはできません。

typescript
function spectralEdit(request: SpectralEditRequest): Float32Array
function spectralEdit(
  samples: Float32Array,
  sampleRate: number,
  options: SpectralEditOptions,
): Float32Array

interface SpectralEditOptions {
  ops: readonly SpectralRegionOp[];  // Region edit ops applied in array order; an empty array returns a copy of the input.
  nFft?: number;  // FFT size; a power of two in `[4, 262144]`. Omit for 2048; 0 is refused.
  hopLength?: number;  // Hop length; `0 < hopLength <= nFft / 2`. Omit for a quarter of `nFft`; 0 is refused.
  window?: WindowType;  // Analysis + synthesis window. Default 'hann'.
  healRadiusFrames?: number;  // Neighbour frames each side used by `'heal'`, at least 1. Omit for 2; 0 is refused.
}

interface SpectralRegionOp {
  startSample?: number;  // Region time start in input samples; past the end reads as the end, a negative value is refused. Default 0. Not with `startSec`.
  startSec?: number;  // Region time start in seconds, rounded to the nearest sample. Not with `startSample`.
  endSample?: number;  // Region time end (exclusive) in input samples. Omit for the end of the signal; a negative value is refused. Not with `endSec`.
  endSec?: number;  // Region time end in seconds, rounded to the nearest sample. Not with `endSample`.
  lowHz?: number;  // Region frequency low edge in Hz; clamped to [0, nyquist]. Default 0.
  highHz?: number;  // Region frequency high edge in Hz, finite and greater than 0; at or above Nyquist reads as Nyquist. Omit for Nyquist.
  gainDb?: number;  // Linear gain in dB for 'gain'/'attenuate'; ignored by 'mute'/'heal'. Default 0.
  mode?: SpectralEditMode;  // Edit mode. Default 'gain'.
}

function voiceChange(request: VoiceChangeRequest): Float32Array
function voiceChange(
  samples: Float32Array,
  sampleRate: number,
  options?: VoiceChangeOptions,
): Float32Array

interface VoiceChangeOptions {
  pitchSemitones?: number;  // Pitch shift in semitones (negative = down). Default 0.
  formantFactor?: number;  // Formant scale factor (>1 brightens, <1 darkens). Default 1.
  formantMode?: FormantMode;  // How `formantFactor` relates to the pitch shift. Default `'relative'`.
}

対応する CLI 例:

bash
sonare pitch-correct vocal.wav --current-midi 68.7 --target-midi 69 -o corrected.wav
sonare note-stretch take.wav --onset-sample 12000 --offset-sample 24000 --ratio 1.25 -o held.wav
sonare voice-change vocal.wav --pitch-semitones 3 --formant-factor 1.05 -o voice.wav

formantMode は formantFactor を何に対して測るかを決めます。'relative'(既定)では、係数はピッチシフトの後にかけるワープで、フォルマントは formantFactor * 2^(pitchSemitones / 12) だけ動きます。'absolute' では、係数はピッチシフトに関係なく入力に対するフォルマントのシフト量になり(1 ならフォルマントは元の位置のまま)ます。relative で formantFactor が [0.55, 1.65] を外れる指定は RangeError になります。absolute には、ピッチシフトに逆らってフォルマントを保てる量に限りがあり、それを超える指定は RangeError になります。値が丸められることはありません。それ以外のモード文字列も RangeError です。CLI では同じ選択を --formant-mode relative|absolute で指定します。

typescript
// 4 半音上げつつ、フォルマントは元の位置に残す
const out = voiceChange(vocal, 48000, { pitchSemitones: 4, formantFactor: 1, formantMode: 'absolute' });

spectralEdit は領域のリストをオプション内の ops で受け取り、nFft は [4, 262144] の範囲の 2 の冪でなければなりません。nFft・hopLength・healRadiusFrames に明示的な 0 を渡すと既定値とは読まれず拒否され(RangeError: spectralEdit: nFft must be a power of two in [4, 262144])、領域の開始・終了サンプルが負なら RangeError です。領域指定の例とオプションの考え方は スペクトル編集 を参照してください。

pitchCorrectTimevarying(...) はスケールにスナップする自動ピッチ補正の経路です。スケールマスク、targetMode、リチューンの効き方の詳細は 編集 DSP を参照してください。

normalize(samples, sampleRate, options?) ​

オーディオを目標レベルに正規化します。mode の既定値は 'peak' で、RMS レベルを目標にする場合は 'rms' を指定します。

typescript
function normalize(request: NormalizeRequest): Float32Array
function normalize(
  samples: Float32Array,
  sampleRate: number,
  options?: OptionsOf<NormalizeRequest>,
): Float32Array

interface NormalizeRequest {
  samples: Float32Array;  // Mono input samples.
  sampleRate: number;  // Sample rate in Hz, an integer in `[8000, 384000]`; there is no default.
  targetDb?: number;  // Finite target level at or below 0 dBFS. Defaults to 0 for `mode: 'peak'` and -20 for `mode: 'rms'`.
  mode?: NormalizeMode;  // Normalization statistic. Default `'peak'`.
}

normalizeStereo(request) ​

ステレオペアを共通の 1 つのゲインで正規化し、ステレオイメージを保ちます。

typescript
function normalizeStereo(request: NormalizeStereoRequest): NormalizeStereoResult   // request form only

interface NormalizeStereoRequest {
  left: Float32Array;  // Left channel samples.
  right: Float32Array;  // Right channel samples.
  sampleRate: number;  // Sample rate in Hz, an integer in `[8000, 384000]`; there is no default.
  targetDb?: number;  // Finite target level at or below 0 dBFS. Defaults to 0 for `mode: 'peak'` and -20 for `mode: 'rms'`.
  mode?: NormalizeMode;  // Normalization statistic. Default `'peak'`.
}

interface NormalizeStereoResult {
  left: Float32Array;  // Normalized left channel.
  right: Float32Array;  // Normalized right channel.
  appliedGainDb: number;  // One figure rather than a pair: the gain is one decision shared by both channels. An all-silent pair is refused.
}

レベルはペア全体から測り、得られたゲインを両チャンネルにそのまま適用します。これがこの関数の要点です。チャンネルごとに別々の目標へ正規化すると、レベルではなく左右のバランスが変わり、意図したパンがセンターに寄ります。ゲインが共通なので、appliedGainDb はチャンネルごとのペアではなく単一の値です。'peak' モードでは大きい側のチャンネルが targetDb に達し、小さい側はその差を保ちます。'rms' モードで targetDb に合わせる量は両チャンネルのサンプルをまとめた RMS、つまりチャンネルごとの値の相加平均ではなく二乗平均平方根で、浮動小数点の出力はフルスケールを超えた値も保持します。

RMS の目標にはピークの余裕を残してください

normalize と normalizeStereo はどちらも、targetDb の既定値が mode: 'peak' では 0、mode: 'rms' では -20 です。RMS の目標に 0 dBFS を明示すると、ピークがフルスケールを超える場合があります。浮動小数点の出力はフルスケールを超えた値も保持します。目標を省略してモードの既定値を使うか、信号のピークに十分な余裕を残す RMS 目標を指定してください。

チャンネルの長さが異なるペアや、両チャンネルが無音のペアは RangeError になります。

trim(samples, sampleRate, options?) ​

オーディオの始めと終わりから無音を除去します。

typescript
function trim(request: TrimRequest): Float32Array
function trim(
  samples: Float32Array,
  sampleRate: number,
  options?: OptionsOf<TrimRequest>,
): Float32Array

interface TrimRequest {
  samples: Float32Array;  // Mono audio samples.
  sampleRate: number;  // Sample rate in Hz, an integer in `[8000, 384000]`; there is no default.
  thresholdDb?: number;  // Silence threshold in dBFS. Default -60.
  frameLength?: number;  // Analysis frame in samples. Default 2048.
  hopLength?: number;  // Hop in samples. Default 512.
}

function trimSilence(request: TrimSilenceRequest): TrimResult
function trimSilence(
  samples: Float32Array,
  sampleRate: number,
  options?: OptionsOf<TrimSilenceRequest>,
): TrimResult

interface TrimSilenceRequest {
  samples: Float32Array;  // Mono audio samples.
  sampleRate: number;  // Sample rate of `samples` in Hz.
  topDb?: number;  // Threshold below the peak, in dB. Default 60.
  frameLength?: number;  // Analysis frame in samples. Default 2048.
  hopLength?: number;  // Hop in samples. Default 512.
}

interface TrimResult {
  audio: Float32Array;  // The trimmed samples.
  startSample: number;  // Index in the input of the first kept sample.
  endSample: number;  // Index in the input where the kept range ends (exclusive).
}

これは Audio レベルの単純なしきい値トリムです。librosa 互換のフレーム RMS / topDb ベースの無音判定と、元音源上の開始・終了サンプル位置が必要な場合は、上の trimSilence(...) を使います。