Skip to content

Node.js ネイティブ API

Node ネイティブバインディングの概要と選び方については、ネイティブバインディング を参照してください。

このページは @libraz/libsonare-native アドオンの関数ごとのリファレンスです。import パスが明示的に @libraz/libsonare でない限り、例はネイティブパッケージを使います。

使用例

typescript
import {
  Audio, analyze, detectBpm, detectKey, detectBeats, version
} from '@libraz/libsonare-native';

// 音声を読み込み
const audio = Audio.fromFile('music.mp3');
const samples = audio.getData();
const sampleRate = audio.getSampleRate();

// 個別の解析
const bpm = detectBpm(samples, sampleRate);
const key = detectKey(samples, sampleRate);
const beats = detectBeats(samples, sampleRate);

// フル解析
const result = analyze(samples, sampleRate);
console.log(`BPM: ${result.bpm}`);
console.log(`キー: ${result.key.name}`);     // "C major" など
console.log(`ビート数: ${result.beatTimes.length}`);

上のアナライザーはどれも同じスペクトログラムを共有して読み出します。下のデモがたどるのがその変換で、BPM とキーをまとめて求めても片方だけの場合とコストがほとんど変わらないのは、これが理由です。

STFT · SPECTRALIDLE
STFT — 時間と周波数を同時に見る

220 Hz から 4 kHz へ上昇するトーン。各列が1つの短時間スペクトルで、明るいほどその周波数のエネルギーが大きい。

オーディオエフェクト

typescript
import { Audio } from '@libraz/libsonare-native';

const audio = Audio.fromFile('music.mp3');

// 倍音成分/打撃成分の分離(HPSS)
const hpssResult = audio.hpss();
const harmonic = audio.harmonic();
const percussive = audio.percussive();

// タイムストレッチ/ピッチシフト
const stretched = audio.timeStretch(1.5);      // 1.5 倍速
const shifted = audio.pitchShift(2.0);         // 2 半音上げ

// ノーマライズと無音トリム
const normalized = audio.normalize(0.0);        // 0 dB
const trimmed = audio.trim(-60.0);

特徴抽出

typescript
import { Audio } from '@libraz/libsonare-native';

const audio = Audio.fromFile('music.mp3');

// スペクトログラム特徴量
const stftResult = audio.stft(2048, 512);
const mel = audio.melSpectrogram(2048, 512, 128);
const mfcc = audio.mfcc(2048, 512, 128, 13);
const chroma = audio.chroma(2048, 512);

// スペクトル特徴量
const centroid = audio.spectralCentroid();
const bandwidth = audio.spectralBandwidth();
const rolloff = audio.spectralRolloff();
const flatness = audio.spectralFlatness();
const zcr = audio.zeroCrossingRate();
const rms = audio.rmsEnergy();

// ピッチ検出
const pitchYin = audio.pitchYin();
const pitchPyin = audio.pitchPyin();
console.log(`Median F0: ${pitchPyin.medianF0.toFixed(1)} Hz`);

単位変換

typescript
import {
  hzToMel, melToHz, hzToMidi, midiToHz,
  hzToNote, noteToHz, framesToTime, timeToFrames
} from '@libraz/libsonare-native';

hzToMel(440);        // → Mel スケール値
melToHz(549.64);     // → Hz
hzToMidi(440);       // → 69
midiToHz(69);        // → 440
hzToNote(440);       // → "A4"
noteToHz('A4');      // → 440

framesToTime(100, 22050, 512);  // → 秒
timeToFrames(2.32, 22050, 512); // → フレームインデックス

API リファレンス

単発 API のリクエストオブジェクト

トップレベルの単発解析・エフェクト・マスタリング・メータリング・特徴量・ミキサー・ボイスチェンジャー関数は、Node でも名前付きリクエストオブジェクトを標準の呼び出し形式として受け取れます。新規コードではこちらを優先してください。位置引数のオーバーロードも互換性のため残り、同じ検証、既定値、結果、エラー、進捗処理へ正規化されます。

ts
const bpm = detectBpm({ samples, sampleRate });
const result = masterAudio({ samples, sampleRate, preset: 'pop' });

対応する *Request TypeScript 型もパッケージからエクスポートされます。

Audio

メソッド説明
Audio.fromFile(path)WAV/MP3 ファイルを読み込み。FFmpeg 有効ビルドでは FFmpeg 対応形式も読み込めます
Audio.fileChannelCount(path)デコードせずに音声ファイルのチャンネル数を取得。モノラルへダウンミックスする fromFile とは別物
Audio.fromBuffer(samples, sampleRate?)Float32Array から作成。sampleRate の既定値は 48000
Audio.fromMemory(data)fromFile と同じ形式対応で、Buffer / Uint8Array をデコード
audio.getData()サンプルのコピーを Float32Array で返します
audio.getSampleRate()サンプルレート(Hz)
audio.getDuration()長さ(秒)
audio.getLength()サンプル数
audio.destroy()ネイティブハンドルを解放。GC でも回収されますが、長時間動くプロセスで確実に解放したい場合に呼び出します

Audio インスタンスは、以下の解析・エフェクト・特徴量関数を同じデフォルト値で メソッドとしても呼び出せます(例: audio.detectBpm()audio.masteringChain(config))。

analyzeSections(...)analyzeMelody(...)cqt(...)vqt(...) などの一部の詳細ヘルパーは スタンドアロン関数のままです。これらには audio.getData()audio.getSampleRate() を渡します。

getData() はコピーを返します

呼び出すたびに新しい Float32Array を確保するため、返された配列に書き込んでも インスタンスが保持する音声は変わりません。あとから audio.detectBpm()audio.masteringChain(...) を呼んでも、読み取られるのは元のサンプルです。 編集後のサンプルを処理するには Audio.fromBuffer(edited, sampleRate) で 新しいインスタンスを作ってください。ループ内で読む場合は配列を自分でキャッシュします。 WASM でも同じ挙動です。

using によるクリーンアップ(Node 22 以上)

ネイティブハンドルを持つクラス(AudioRealtimeEngineProjectMixerClipPageProvider)はすべて [Symbol.dispose] を実装しています。そのため Node 22 以上では using キーワードを使うと、スコープを抜けるときに例外発生時でも 安全に自動でクリーンアップできます。

typescript
import { RealtimeEngine } from '@libraz/libsonare-native';

function render() {
  using engine = new RealtimeEngine(48000, 128);
  engine.setTempo(120);
  // 例外が起きても、このスコープを抜けるときにハンドルが解放されます。
}

Node 22 未満では、これまでどおり try/finally で明示的に解放するパターンを使ってください。 すべてのハンドルクラスでネイティブの正規の解放メソッドは destroy() です。ProjectMixer は WASM 互換のエイリアスとして delete() も公開します。ハンドルは最終的に GC でも 回収されますが、using や明示的な解放のほうが決定的なクリーンアップになるため、 長時間動くプロセスではそちらを推奨します。

RealtimeVoiceChanger も明示的な destroy() に加えて [Symbol.dispose] を実装しているため、 using を使えます。StreamingMasteringChainStreamingEqualizerStreamAnalyzer も同様に 冪等な destroy()[Symbol.dispose] を公開しており、決定的に解放できます。

解析関数

関数戻り値説明
detectBpm(samples, sampleRate?)numberテンポ(BPM)
detectKey(samples, sampleRate?)Keyルート、モード、確信度
detectBeats(samples, sampleRate?)Float32Arrayビート位置
detectOnsets(samples, sampleRate?)Float32Arrayオンセット位置
detectChords(samples, sampleRate?, minDuration?, smoothingWindow?, threshold?, useTriadsOnly?, nFft?, hopLength?, useBeatSync?, useHmm?, hmmBeamWidth?, useKeyContext?, keyRoot?, keyMode?, detectInversions?, chromaMethod?)ChordAnalysisResultコード進行(開始/終了時刻付き)。threshold 未満のフレームは明示的な N.C. 区間として返ります。末尾の引数で HMM 平滑化・キーコンテキスト・転回形・クロマ手法(既定 'stft')を制御
detectDownbeats(samples, sampleRate?)Float32Array小節頭(ダウンビート)の位置
detectKeyCandidates(samples, sampleRate?, options?)KeyCandidate[]相関スコア付きのキー候補ランキング
analyze(samples, sampleRate?)AnalysisResult1 回の呼び出しで、BPM と順位付き BPM 仮説、キー、拍子と順位付き拍子候補、ビート、コード、セクション、音色、ダイナミクス、リズム、メロディ、フォームを解析。以下の専用 detect*analyze* 関数は、個別解析やパラメータ指定の解析向けに引き続き利用できます
analyzeWithProgress(samples, sampleRate?, onProgress?)AnalysisResultanalyze と同じ。長尺入力向けに (progress, stage) コールバックを受け取ります
analyzeBpm(samples, sampleRate?, options?)BpmAnalysisResult確信度と候補付きテンポ。options: bpmMinbpmMaxstartBpmnFfthopLengthmaxCandidates
analyzeRhythm(samples, sampleRate?, options?)RhythmResult拍子・グルーブ・シンコペーション。options: bpmMinbpmMaxstartBpmnFfthopLength
analyzeDynamics(samples, sampleRate?, options?)DynamicsResultダイナミックレンジ・ラウドネスレンジ・クレストファクター。options: windowSechopLengthcompressionThreshold
analyzeTimbre(samples, sampleRate?, options?)TimbreResult明るさ・暖かさ・密度・粗さ・複雑さと、窓ごとの timbreOverTimeoptions: nFfthopLengthnMelsnMfccwindowSec
analyzeSections(samples, sampleRate?, options?)Section[]構造セクション(イントロ/Aメロ/サビなど)と時刻。options: nFfthopLengthminSectionSec。長尺入力では境界グリッドがプーリングされる場合があるため、配置には各セクションの start / end を使います
analyzeMelody(samples, sampleRate?, options?)MelodyResult主旋律の輪郭(フレームごとの F0)。options: fminfmaxframeLengthhopLengththresholdusePyincenter
detectAcoustic(samples, sampleRate?, options?)AcousticResult録音からのルーム音響(残響が 60 dB 減衰するまでの時間である RT60 など)。options: nOctaveBandsnThirdOctaveSubbandsminDecayDbnoiseFloorMarginDb
analyzeImpulseResponse(samples, sampleRate?, nOctaveBands?, minDecayDb?)AcousticResult測定済みインパルス応答(IR)からのルーム音響。minDecayDb は減衰フィットのしきい値(既定 30
estimateRoom(samples, sampleRate?, options?)RoomEstimateResult体積、寸法、DRR(直接音と残響音のエネルギー比)、吸音率バンド、RT60 バンド、信頼度を含む等価ルーム推定
synthesizeRir(options?)RirResultシューボックス形状からのモノラル RIR(ルームインパルス応答)
roomMorph(samples, sampleRate, options?)Float32Array目標ルームへ寄せるオフラインのルームモーフィング
lufs(samples, sampleRate?)LufsResult統合値、最後のモーメンタリー/ショートターム窓、EBU R128 の最大値(Max-M / Max-S)、ラウドネスレンジ
lufsInterleaved(samples, channels, sampleRate?)LufsResultインターリーブサンプルからチャンネル重み付きマルチチャンネルラウドネスを測定
ebur128LoudnessRange(samples, sampleRate?)numberEBU R128 準拠のラウドネスレンジ(LRA、LU 単位)
momentaryLufs(samples, sampleRate?)Float32Arrayモーメンタリーラウドネス(400ms)の時系列
shortTermLufs(samples, sampleRate?)Float32Arrayショートタームラウドネス(3s)の時系列
version()stringライブラリバージョン
voiceChangerAbiVersion()numberリアルタイムボイスチェンジャー POD 設定の ABI バージョン。プリセット JSON の schemaVersion とは別
voiceCharacterPresetId(preset)VoicePresetId | null正規の voice-character プリセット ID。未知の数値序数は null、未知の文字列 ID は例外
realtimeVoiceChangerPresetConfig(preset)RealtimeVoiceChangerConfigJSON 解析なしで、組み込みボイスプリセットの解決済みフラット POD 設定を返す。未知のプリセット名や範囲外の序数では例外を投げる
hasFfmpegSupport()boolean読み込まれたネイティブアドオンが FFmpeg デコードに対応しているか

デフォルトの sampleRate は、ヘルパーの種類によって異なります。

ヘルパーデフォルト sampleRate
楽曲解析、エフェクト、特徴量、ラウドネス系ヘルパー22050
ネイティブ版の analyzeImpulseResponsedetectAcousticestimateRoomsynthesizeRir48000

主要なヘルパーは Audio インスタンスメソッドとしても利用できます。ただし、analyzeSections(...)analyzeMelody(...)cqt(...)vqt(...) など一部の詳細ヘルパーは、スタンドアロン関数として audio.getData()audio.getSampleRate() を渡します。

下の表は Node ネイティブ版のシグネチャです。WASM パッケージも同じ camelCase 名を使いますが、sampleRate の後ろに必須引数がある関数では、その sampleRate 位置も渡す必要があります。ブラウザ向けの正確なシグネチャは JavaScript API を参照してください。

非同期版(Node 専用)

Node アドオンは、Promise 返却版も公開しています。これらは DSP パイプラインを libuv のワーカースレッドで実行するため、JS イベントループをブロックしません。

戻り値の形は同期版と同じで、これらの関数自体は Node ネイティブ専用です。ブラウザでは @libraz/libsonare/workerOfflineWorkerClient を使うと、同名関数ではなくタスク形式の API で解析とマスタリングを Web Worker 上へ移せます。

非同期版では進捗コールバックを使えません。進捗が必要な場合は onProgress 付きの同期版を使います。並行実行だけが目的なら、複数の非同期呼び出しを同時に走らせます。

関数戻り値説明
analyzeAsync(samples, sampleRate?)Promise<AnalysisResult>analyze(...) の非同期版
masterAudioAsync(samples, sampleRate?, presetName?, overrides?)Promise<MasteringChainResult>masterAudio(...) の非同期版
masterAudioStereoAsync(left, right, sampleRate?, presetName?, overrides?)Promise<MasteringChainStereoResult>masterAudioStereo(...) の非同期版

エフェクト関数

関数戻り値説明
hpss(samples, sr?, kernelHarmonic?, kernelPercussive?, nFft?, hopLength?, hardMask?)HpssResult倍音成分/打撃成分の分離(HPSS)。既定は nFft=2048hopLength=512hardMask=false
hpssWithResidual(samples, sr?, kernelHarmonic?, kernelPercussive?, nFft?, hopLength?, hardMask?)HpssWithResidualResult倍音、打撃、残差を返す HPSS。同じ STFT/マスクオプションを受け取ります
harmonic(samples, sr?)Float32Array倍音成分の抽出
percussive(samples, sr?)Float32Array打撃成分の抽出
timeStretch(samples, sampleRate, rate, nFft?, hopLength?)Float32Arrayピッチを変えずにテンポを変更。既定は nFft=2048hopLength=512
phaseVocoder(samples, sampleRate, rate, nFft?, hopLength?)Float32Array直接のフェーズボコーダー時間伸縮
pitchShift(samples, sampleRate, semitones, nFft?, hopLength?)Float32Array長さを変えずにピッチを変更。既定は nFft=2048hopLength=512
remix(samples, intervals, sr?, alignZeros?)Float32Arrayサンプル区間の並べ替え/連結
normalize(samples, sr?, targetDb?, mode?)Float32Array目標ピーク/RMS dB にノーマライズ(mode: 'peak' または 'rms'、既定 'peak'
trim(samples, sr?, thresholdDb?, frameLength?, hopLength?)Float32Array無音区間をトリム(既定: -60.0 dB、frameLength=2048hopLength=512
resample(samples, srcSr, targetSr)Float32Array目標サンプルレートへリサンプリング
pitchCorrectToMidi(samples, sr, currentMidi, targetMidi)Float32Array保持された音を MIDI ピッチ間で補正
pitchCorrectToMidiTimevarying(samples, f0Hz, targetMidi, sr?, hopLength?, voiced?, voicedProb?)Float32Array追跡したピッチ輪郭を、フレーム単位で固定の音へリチューン。voicedVoicedFlags を受け取る
pitchCorrectTimevarying(samples, f0Hz, sr?, hopLength?, options?)Float32Array追跡したピッチ輪郭をスケールまたは固定音へスナップ。optionsPitchCorrectOptions で、その voiced フィールドも VoicedFlags を受け取る
noteStretch(samples, sr?, options?)Float32Array1 つの音の区間をその場でタイムストレッチ。options{ onsetSample, offsetSample, stretchRatio }
voiceChange(samples, sr?, options?)Float32Arrayボイス変換のためのピッチ+フォルマントシフト。options{ pitchSemitones, formantFactor }

trim(...) は単純なしきい値ベースの編集ヘルパーです。下の trimSilence(...) は librosa 互換のフレーム RMS ベースのヘルパーで、元音源上のサンプル範囲も返します。

hpss(...)hpssWithResidual(...) は、メディアンフィルターのカーネルを既定で kernelHarmonic=31kernelPercussive=31 とします。リクエストオブジェクト形式でも 位置引数形式と同じ nFfthopLengthhardMask の名前を使います。

VoicedFlagsInt32Array | Uint8Array | Float32Array | readonly number[] | readonly boolean[] です。PitchResult.voicedFlag が返す boolean[] を、変換なしで そのままピッチ補正へ渡せます。

typescript
const pitch = pitchPyin(samples, sampleRate);
const tuned = pitchCorrectToMidiTimevarying(
  samples,
  pitch.f0,
  69,
  sampleRate,
  512,
  pitch.voicedFlag,   // boolean[] is accepted as-is
  pitch.voicedProb,
);

voicedvoicedProb は、どちらも f0Hz と同じ長さである必要があります。長さが 食い違うと RangeError'voiced must have the same length as f0Hz')を投げます。 SonareError ではないため isSonareError では捕捉できません。

特徴抽出関数

関数戻り値説明
stft(samples, sr?, nFft?, hopLength?)StftResult短時間フーリエ変換
stftDb(samples, sr?, nFft?, hopLength?)StftDbResultdB 単位の STFT
melSpectrogram(samples, sr?, nFft?, hopLength?, nMels?)MelSpectrogramResultメルスペクトログラム
mfcc(samples, sr?, nFft?, hopLength?, nMels?, nMfcc?, fmin?, fmax?, htk?, lifter?)MfccResultメル周波数ケプストラム係数(lifter 既定 0 = リフタリングなし)
chroma(samples, sr?, nFft?, hopLength?)ChromaResultクロマ特徴量
spectralCentroid(samples, sr?, nFft?, hopLength?)Float32Arrayフレームごとのスペクトル重心
spectralBandwidth(samples, sr?, nFft?, hopLength?)Float32Arrayフレームごとのスペクトル帯域幅
spectralRolloff(samples, sr?, nFft?, hopLength?, rollPercent?)Float32Arrayフレームごとのスペクトルロールオフ
spectralFlatness(samples, sr?, nFft?, hopLength?)Float32Arrayフレームごとのスペクトル平坦度
spectralContrast(samples, sr?, nFft?, hopLength?, nBands?, fmin?, quantile?)Matrix2dResultスペクトルコントラスト。形状は (nBands + 1) x nFrames
spectralEdit(samples, sr, ops?, options?)Float32Arraygainattenuatemuteheal を使う領域指定 STFT 編集
polyFeatures(samples, sr?, nFft?, hopLength?, order?)Matrix2dResultフレームごとの多項式スペクトル係数
zeroCrossingRate(samples, sr?, frameLength?, hopLength?)Float32Arrayフレームごとのゼロ交差率
zeroCrossings(samples, threshold?, refMagnitude?, pad?, zeroPos?)Int32Arrayゼロ交差サンプル位置
rmsEnergy(samples, sr?, frameLength?, hopLength?)Float32Arrayフレームごとの RMS エネルギー
pitchYin(samples, sr?, frameLength?, hopLength?, fmin?, fmax?, threshold?, fillNa?)PitchResultYIN ピッチ推定。無声音の f0fillNa が true でない限り NaN
pitchPyin(samples, sr?, frameLength?, hopLength?, fmin?, fmax?, threshold?, fillNa?)PitchResultpYIN ピッチ推定。無声音の f0fillNa が true でない限り NaN
pitchTuning(frequencies, resolution?, binsPerOctave?)number周波数列からチューニングずれを推定
estimateTuning(samples, sr?, nFft?, hopLength?, resolution?, binsPerOctave?)number音声からチューニングずれを推定
cqt(samples, sr?, hopLength?, fmin?, nBins?, binsPerOctave?)CqtResult定 Q 変換の振幅
vqt(samples, sr?, hopLength?, fmin?, nBins?, binsPerOctave?, gamma?)CqtResult可変 Q 変換の振幅(gamma で Q を制御)
chromaCqt(samples, sr?, hopLength?, nChroma?){ nChroma, nFrames, data }Constant-Q クロマグラム(librosa.feature.chroma_cqt 相当)
nnlsChroma(samples, sr?, options?){ nChroma, nFrames, data }NNLS クロマグラム(音符活性化クロマ)。options.hopLength の既定値は 512
decompose(s, nFeatures, nFrames, nComponents, nIter?, beta?, init?)DecomposeResult行優先スペクトログラムから NMF(非負値行列因子分解)の分解行列を返す。init を選択できる('random' 既定、'nndsvd'
hybridCqt(samples, sr?, hopLength?, fmin?, nBins?, binsPerOctave?)CqtResultハイブリッド CQT 振幅(低域は真の CQT、高域は擬似 CQT)
pseudoCqt(samples, sr?, hopLength?, fmin?, nBins?, binsPerOctave?)CqtResult近似(擬似)CQT 振幅(単一 FFT)
bassChroma(samples, sr?, hopLength?, nChroma?)ChromaResult低域重視クロマ(低音域のピッチクラス分布)
chromaCens(samples, sr?, hopLength?, nChroma?)ChromaResultCENS エネルギー正規化・平滑化クロマ
onsetStrengthMulti(samples, sr?, nFft?, hopLength?, nMels?, nBands?){ nBands, nFrames, data }マルチバンドオンセット強度(nBands 既定 3、data は行優先 [nBands x nFrames]
nnFilter(s, nFeatures, nFrames, aggregate?, k?, width?)Matrix2dResult近傍フィルタ
onsetEnvelope(samples, sr?, nFft?, hopLength?, nMels?)Float32Arrayオンセット強度の包絡線。フレームごとにエネルギーがどれだけ急に立ち上がったかを表し、テンポグラム系の入力になります

主な既定値は、nFft=2048hopLength=512nMels=128nMfcc=20、ピッチ検出の fmin=65.0fmax=2093.0threshold=0.1rollPercent=0.85 です。

CQT/VQT は fmin=32.70319566 Hz(C1)、nBins=84binsPerOctave=12 を使います。VQT の既定 gamma=-1 は ERB 由来の帯域幅を自動選択します。chromaCqt の既定は nChroma=12nBins=252binsPerOctave=36 です。bassChromachromaCensnChroma=12onsetStrengthMultinBands=3decomposenIter=50beta=2init='random' が既定です。

逆再構成関数

メルスペクトログラムや MFCC 行列から、スペクトルや音声を再構成します。位相は Griffin-Lim で推定するため往復はロスを伴います。詳細は 逆変換特徴量 を参照してください。

関数戻り値説明
melToStft(mel, nMels, nFrames, sampleRate?, nFft?, fmin?, fmax?, htk?)InverseStftResultメルスペクトログラムから線形 STFT パワーへ
melToAudio(mel, nMels, nFrames, sr?, nFft?, hopLength?, fmin?, fmax?, nIter?, htk?)Float32Arrayメルスペクトログラムから音声へ(Griffin-Lim)
mfccToMel(mfcc, nMfcc, nFrames, nMels?, lifter?)InverseMelResultMFCC 係数からメルスペクトログラムへ
mfccToAudio(mfcc, nMfcc, nFrames, nMels?, sampleRate?, nFft?, hopLength?, fmin?, fmax?, nIter?, htk?)Float32ArrayMFCC 係数から音声へ
cqtToAudio(magnitude, nBins, nFrames, sampleRate?, hopLength?, fmin?, binsPerOctave?, nIter?)Float32Arrayrow-major CQT 振幅行列から音声へ(Griffin-Lim)
vqtToAudio(magnitude, nBins, nFrames, sampleRate?, hopLength?, fmin?, binsPerOctave?, gamma?, nIter?)Float32Arrayrow-major VQT 振幅行列から音声へ(Griffin-Lim)

librosa 互換ヘルパー

対応する librosa 関数の挙動に 合わせています。マッピングの全体像は librosa 互換性 を参照してください。

各ヘルパーの位置づけ

  • preemphasis / deemphasis — 高域を持ち上げる/戻す古典的な 1 タップ IIR の前処理。
  • trimSilence / splitSilence — 前後無音のトリムや、無音区間での区切り出し。
  • frameSignal / padCenter / fixLength / fixFrames — 固定フレーム DSP に通すためのフレーミング・サイズ揃え。
  • peakPick / vectorNormalize — 1 次元信号のピーク検出と、ベクトルのノルム正規化。
  • pcen — メルスペクトログラム向けの動的レンジ圧縮。
  • tonnetz — クロマを 6 次元のハーモニック空間へ射影。
  • tempogram / plp — オンセット包絡線から構築するテンポ表現と支配的なパルスの抽出。
関数戻り値説明
preemphasis(samples, coef?, zi?)Float32Arrayプリエンファシス
deemphasis(samples, coef?, zi?)Float32Arrayディエンファシス
trimSilence(samples, topDb?, frameLength?, hopLength?){ audio: Float32Array; startSample: number; endSample: number }librosa.effects.trim。しきい値 trim(...) とは別物
splitSilence(samples, topDb?, frameLength?, hopLength?)Int32Arraylibrosa.effects.split[start0, end0, start1, end1, ...] のフラット配列
frameSignal(samples, frameLength, hopLength){ nFrames: number; frames: Float32Array }librosa.util.frame(row-major)
padCenter(values, targetSize, padValue?)Float32Arraylibrosa.util.pad_center
fixLength(values, targetSize, padValue?)Float32Arraylibrosa.util.fix_length
fixFrames(frames, xMin?, xMax?, pad?)Int32Arraylibrosa.util.fix_frames
peakPick(values, preMax, postMax, preAvg, postAvg, delta, wait)Int32Arraylibrosa.util.peak_pick
vectorNormalize(values, normType?, threshold?)Float32Arraylibrosa.util.normalizenormType: 0=inf, 1=L1, 2=L2, 3=power。Node wrapper の threshold 既定値は 0.0、WASM は 1e-12
pcen(values, nBins, nFrames, options?)Float32Arraylibrosa.pcen(row-major のメル入力)
tonnetz(chromagram, nChroma, nFrames)Float32Arraylibrosa.feature.tonnetz[6 x nFrames]
tempogram(onsetEnvelope, sr?, hopLength?, winLength?, mode?){ nFrames: number; winLength: number; data: Float32Array }librosa.feature.tempogrammode'autocorrelation'(既定)または 'cosine'
fourierTempogram(onsetEnvelope, sr?, hopLength?, winLength?){ nBins: number; nFrames: number; data: Float32Array }librosa.feature.fourier_tempogram
cyclicTempogram(onsetEnvelope, sr?, hopLength?, winLength?, center?, norm?, bpmMin?, nBins?){ nFrames: number; nBins: number; data: Float32Array }巡回(テンポオクターブ不変)テンポグラム
tempogramRatio(tempogramData, winLength?, sr?, hopLength?, factors?)Float32Arraylibrosa.feature.tempogram_ratio。factors の既定値は [0.5, 1, 2, 3, 4]
plp(onsetEnvelope, sr?, hopLength?, tempoMin?, tempoMax?, winLength?)Float32Arraylibrosa.beat.plp

変換関数

関数説明
hzToMel(hz)ヘルツ → Mel スケール
melToHz(mel)Mel スケール → ヘルツ
hzToMidi(hz)ヘルツ → MIDI ノート番号
midiToHz(midi)MIDI ノート番号 → ヘルツ
hzToNote(hz)ヘルツ → 音名(例: "A4")
noteToHz(note)音名 → ヘルツ
framesToTime(frames, sr?, hopLength?)フレームインデックス → 秒(sr 既定 22050hopLength 既定 512
timeToFrames(time, sr?, hopLength?)秒 → フレームインデックス(sr 既定 22050hopLength 既定 512
framesToSamples(frames, hopLength?, nFft?)フレームインデックス → サンプルインデックス(librosa.frames_to_samples
samplesToFrames(samples, hopLength?, nFft?)サンプルインデックス → フレームインデックス(librosa.samples_to_frames
powerToDb(values, ref?, amin?, topDb?)パワー → dB(librosa.power_to_db
amplitudeToDb(values, ref?, amin?, topDb?)振幅 → dB(librosa.amplitude_to_db
dbToPower(values, ref?)dB → パワー
dbToAmplitude(values, ref?)dB → 振幅

メータリング関数

レベル・ダイナミクス・ステレオイメージを測る単体メーターです。各関数は validate フラグ(既定 true)を持つ options を任意で受け取ります。ホットパスでは { validate: false } を渡して NaN/Inf 入力チェックを省略できます。ステレオメーターは leftright が同じ長さである必要があります。

関数戻り値説明
meteringPeakDb(samples, sr?, options?)numberサンプルピーク(dBFS)
meteringRmsDb(samples, sr?, options?)numberRMS レベル(dBFS)
meteringCrestFactorDb(samples, sr?, options?)numberクレストファクター(ピーク − RMS、dB)。値が大きいほどピークとレベルの差が大きく、圧縮されていない信号を意味します
meteringCrestFactorDbStereo(request)numberチャンネルペアのクレストファクター(dB)。ピークは左右をまたいで取り、RMS は左右まとめて測ります。リクエスト専用で、MeteringStereoRequest{ left, right, sampleRate?, validate? })だけを受け取り、位置引数のオーバーロードはありません
meteringDcOffset(samples, sr?, options?)number平均(DC)オフセット、リニア振幅
meteringTruePeakDb(samples, sr?, oversampleFactor?, options?)numberサンプル間ピーク(ISP、いわゆる True Peak。サンプル点の間で波形が到達する最大値、dBFS)。oversampleFactor は 1..16 の 2 の冪(既定 4)
meteringDetectClipping(samples, sr?, options?)ClippingReportクリップしたサンプルの連続区間。optionsthreshold(既定 0.999)と minRegionSamples(既定 1)を指定
meteringDynamicRange(samples, sr?, options?)DynamicRangeReportスライディングウィンドウのダイナミックレンジ。optionswindowSechopSeclowPercentilehighPercentile を指定(省略時は既定値の窓 3 秒・ホップ 1 秒・low 0.10・high 0.95)
meteringStereoCorrelation(left, right, sr?, options?)number非中心化相関(コサイン類似度)、−1..1
meteringStereoWidth(left, right, sr?, options?)numberサイド/ミッドのエネルギー比。0 = モノラル、約 1 = 広いステレオ。上限なし(ミッドが無音なら Infinity
meteringVectorscope(left, right, sr?, options?)VectorscopeReportサンプルごとのミッド/サイド点列
meteringPhaseScope(left, right, sr?, options?)PhaseScopeReportフェーズスコープの点列と要約統計
meteringSpectrum(samples, sr?, options?)SpectrumReport信号全体に対する Welch 平均の振幅/パワー/dB スペクトラム(50% 重複する Hann フレームで平均)。optionsnFftapplyOctaveSmoothingoctaveFractiondbRefdbAmin を指定
meteringSpectrumFrame(samples, sr?, frameOffset?, options?)SpectrumReport単一フレーム(Hann 窓 1 回分)の振幅/パワー/dB スペクトラム。meteringSpectrum と異なり時間平均しません。frameOffset で解析フレームの開始位置を指定
meteringSilenceRatio(samples, sr?, thresholdDb?, frameLength?, hopLength?, options?)numberRMS が thresholdDb を下回るフレームの割合(既定: -45 dBFS、frameLength=1024hopLength=256
waveformPeaks(samples, channels, options?)WaveformPeaksReportインターリーブ音声からチャンネルごとの min/max 波形バケットを算出。options.samplesPerBucket の既定値は 512
waveformPeakPyramid(samples, channels, options?)WaveformPeaksReport[]複数のズームレベル向けの波形ピークバケット。options.samplesPerBucketLevels の既定値は [512, 1024, 2048, 4096]

左右が逆相になりうる素材では meteringCrestFactorDbStereo(...) を使ってください。逆相のペアは meteringCrestFactorDb(...) が必要とする 0.5 * (left + right) のダウンミックスで打ち消し合い、RMS が小さく出るぶんクレストファクターが過大に出ます。完全な逆相ペアでの実測値は、ステレオ版が 11.64 dB、ダウンミックス経由が 0.00 dB でした。

マスタリング解析関数

説明可能なマスタリングのヘルパーは JSON 文字列を返します。正確な形は マスタリングアシスタント を参照してください。下のステレオ版はいずれもリクエスト専用で、リクエストオブジェクト 1 つだけを受け取ります。位置引数のオーバーロードはなく、位置引数で呼ぶと例外になります。

関数戻り値説明
masteringAudioProfileStereo(request)stringチャンネルペアのマスタリングアシスタントプロファイルを JSON で返す。MasteringAudioProfileStereoRequest を受け取る
masteringAssistantSuggestStereo(request)stringチャンネルペアに対するマスタリングの提案を JSON で返す。MasteringAssistantSuggestStereoRequest を受け取る
masteringStreamingPreviewStereo(request)stringチャンネルペアの配信ラウドネスのプレビューを JSON で返す。MasteringStreamingPreviewStereoRequest を受け取る。platforms を省略するか空配列を渡すと、例外ではなく組み込みの Spotify / Apple Music / YouTube のセット(3 行)にフォールバックする
typescript
import { masteringAudioProfileStereo, masteringStreamingPreviewStereo } from '@libraz/libsonare-native';

const profile = JSON.parse(masteringAudioProfileStereo({ left, right, sampleRate }));
const preview = JSON.parse(
  masteringStreamingPreviewStereo({
    left,
    right,
    sampleRate,
    platforms: [{ name: 'Spotify', targetLufs: -14, ceilingDb: -1 }],
  }),
);

ステレオ素材ならステレオ版を使ってください。モノラル版は 0.5 * (left + right) のダウンミックスを計測するため、相関の低い素材では約 6 dB 低く出ます。積分ラウドネス、そこから導かれる正規化ゲイン、天井に当たるリスクの判断が、そろって同じぶんだけ過小に報告されます。相関の低いピンクノイズのペア(48 kHz、4 秒)での実測値は、ダウンミックス経由が -22.55 LUFS、ステレオ版が -16.44 LUFS で、差は 6.11 dB でした。Spotify の normalizationGainDb もダウンミックス経由が +8.55、ステレオ版が +2.44 です。

ステレオプロファイルのうち、左右両チャンネルから計測されるのは loudness ブロックだけです。積分 LUFS と LRA はチャンネル加算したプログラムから求め、True Peak は左右の大きいほうを採ります。スペクトル、ダイナミクス、テンポの各フィールドはダウンミックス上で計測されるため、masteringAudioProfile の値とそのまま比較できます。

リクエスト型の名前がバインディングごとに違います

Node はプロファイル用と提案用で 2 つの型名を宣言しています。MasteringAudioProfileStereoRequestMasteringAssistantSuggestStereoRequest を継承し、フィールドを追加しません。WASM パッケージは両方に共通の MasteringStereoParamsRequest を使います。フィールドは同一なので、両者の間でコードを移植するときに変えるのは型名だけです。

スケール量子化

ピッチ補正ターゲットを構築するための 12-TET(12 平均律)スケールヘルパーです。

modeMask は 12 ビットのマスクです。ビット i が、rootPitchClass、C = 0)を基準とした i 番目のピッチクラスを有効化します。自然な長調は 0b101010110101 です。

referenceMidi はチューニング基準音です。A4 = 69 にするには 0 を渡します。pitchCorrectToMidi(...) と組み合わせて最も近いスケール構成音へリチューンします。

関数戻り値説明
scaleQuantizeMidi(root, modeMask, midi, referenceMidi?)number小数を含む MIDI 番号を最も近い有効なピッチクラスへスナップ
scaleCorrectionSemitones(root, modeMask, midi, referenceMidi?)number補正量(量子化後 − 入力)をセミトーンで返す
scalePitchClassEnabled(root, modeMask, pitchClass)booleanpitchClass(0..11)が root を基準に有効か

ストリーミング/リアルタイムクラス

一括処理の関数に加えて、ネイティブアドオンは WASM ビルドと同じストリーミング/リアルタイムクラスを公開します。

クラス用途
StreamAnalyzerブロック単位の解析。時間とともに更新される BPM/キー推定と readFramesSoareadFramesI16readFramesU8リアルタイムストリーミング を参照。
StreamingEqualizerリアルタイムセーフなブロック EQ。
StreamingMasteringChainブロックごとに進めるマスタリングレンダリング(ネイティブバインディング で解説)。
RealtimeVoiceChangerプリセット式のライブ音声チェーン。ブロック処理向け。
MixerJSON シーンから構築する永続マルチストリップミキサー。ミキシングエンジン を参照。
RealtimeEngineDAW 風ホスティング向けのトランスポート/クリップ/オートメーションエンジン。
typescript
import { StreamAnalyzer } from '@libraz/libsonare-native';

const analyzer = new StreamAnalyzer({ sampleRate: 48000, computeMel: true, computeOnset: true });
analyzer.process(block);                 // Float32Array のブロックを渡す
const frames = analyzer.readFramesSoa(analyzer.availableFrames());
const stats = analyzer.stats();          // stats.estimate.bpm / .key(PitchClass の整数)

Node ネイティブでは float の Structure-of-Arrays 読み出しの正式名は readFramesSoa(...) です。バインディング間の命名を揃えるためのエイリアス readFrames(...) も公開しており、これは WASM パッケージが同じ操作に使う名前と一致します。

Node ネイティブの RealtimeVoiceChanger{ sampleRate, maxBlockSize, channels, preset } で構築します。

処理には processMono(...)processMonoInto(...)processInterleaved(...)processPlanarStereo(...) を使います。

オフラインの便利用途では、voiceChangeRealtime(...) が同じプリセットチェーンでモノラルバッファ全体を 512 サンプルブロック単位に処理します。

typescript
import {
  RealtimeVoiceChanger,
  realtimeVoiceChangerPresetConfig,
  realtimeVoiceChangerPresetNames,
  voiceCharacterPresetId,
  voiceChangeRealtime,
} from '@libraz/libsonare-native';

const changer = new RealtimeVoiceChanger({
  sampleRate: 48000,
  maxBlockSize: 128,
  channels: 1,
  preset: 'bright-idol',
});

const blockOut = changer.processMono(inputBlock);
const rendered = voiceChangeRealtime(vocal, 48000, 'soft-whisper');
const presetConfig = realtimeVoiceChangerPresetConfig('bright-idol');
console.log(
  voiceCharacterPresetId(1),
  realtimeVoiceChangerPresetNames(),
  presetConfig,
  changer.latencySamples(),
  blockOut,
  rendered,
);
changer.destroy();

RealtimeEngine はクラスとしては共有されていますが、実行環境ごとに細部が異なります。

Runtime違い
WASMengineCapabilities() を追加し、構築前に ABI 互換性を確認します。キャプチャバッファは正規形の setCaptureBuffer(numChannels, capacityFrames) で設定します。
Node ネイティブengineAbiVersion() を公開します。ブラウザ向けの機能確認ヘルパーはありません。キャプチャバッファは WASM と同じ正規形 setCaptureBuffer(numChannels, capacityFrames) に加えて、後方互換のために非推奨の setCaptureBuffer(channels: Float32Array[]) も残しています。

Project.create() は空のプロジェクトを作成します。setAssistSidecar(...)assistSidecars() でモジュール固有の不透明なメタデータを保持でき、 ProjectAutomationTargetKindtargetKind でオートメーションレーンの対象種別を付けられます。 RealtimeEngine.setTrackMonitorMode(laneIndex, mode, renderFrame?)'off''pfl'(pre-fader listen=フェーダー前で試聴)、'afl'(after-fader listen=フェーダー後で試聴)、 および対応する数値序数を受け取ります。トラック/ミキサーのパン則セッターは、下記の PanLawInput エイリアスを受け取ります。

型定義

typescript
interface Key {
  root: string;        // ピッチクラス名。例: "C"、"C#"、"A"
  mode: string;        // モード名。例: "major"、"minor"
  confidence: number;
  name: string;        // "C major"、"A minor" など
  shortName: string;   // "C"、"Am" など
}

interface TimeSignature {
  numerator: number;
  denominator: number;
  confidence: number;
}

interface BpmHypothesis {
  value: number;
  confidence: number;
  relation: 'primary' | 'half' | 'double' | 'other';
}

interface AnalysisResult {
  bpm: number;
  bpmConfidence: number;
  bpmCandidates: BpmHypothesis[];
  key: Key;
  timeSignature: TimeSignature;
  timeSignatureCandidates: TimeSignature[];
  beatTimes: Float32Array;                       // beats[].time から導出
  beats: Array<{ time: number; strength: number }>;
  chords: AnalysisChord[];                       // 検出したコード進行
  sections: AnalysisSection[];                   // 楽曲構造セクション
  timbre: AnalysisTimbre;                        // 音色の集約サマリー
  dynamics: AnalysisDynamics;                    // ダイナミクスの集約サマリー
  rhythm: AnalysisRhythm;                        // リズムの集約サマリー
  melody: AnalysisMelody;                        // 旋律輪郭のサマリー
  form: string;                                  // 楽曲形式ラベル。例: "AABA"
}
// analyze() は上記のフル結果を返します。専用の detect*/analyze* 関数は、
// 個別解析やパラメータ指定の解析向けに引き続き利用できます。

interface HpssResult {
  harmonic: Float32Array;
  percussive: Float32Array;
  sampleRate: number;
}

interface StftResult {
  nBins: number;
  nFrames: number;
  nFft: number;
  hopLength: number;
  sampleRate: number;
  magnitude: Float32Array;  // nBins × nFrames, row-major
  power: Float32Array;      // nBins × nFrames, row-major
}

interface StftDbResult {
  nBins: number;
  nFrames: number;
  db: Float32Array;         // dB 単位のパワー
}

interface MelSpectrogramResult {
  nMels: number;
  nFrames: number;
  sampleRate: number;
  hopLength: number;
  power: Float32Array;      // nMels × nFrames, row-major
  db: Float32Array;         // nMels × nFrames, row-major
}

interface MfccResult {
  nMfcc: number;
  nFrames: number;
  coefficients: Float32Array;  // nMfcc × nFrames, row-major
}

interface ChromaResult {
  nChroma: number;
  nFrames: number;
  sampleRate: number;
  hopLength: number;
  features: Float32Array;   // nChroma × nFrames, row-major
  meanEnergy: number[];     // nChroma 個の値
}

interface PitchResult {
  f0: Float32Array;         // フレームごとの基本周波数(Hz)
  voicedProb: Float32Array; // フレームごとの有声確率(0–1)
  voicedFlag: boolean[];    // フレームごとの有声/無声判定
  nFrames: number;
  medianF0: number;
  meanF0: number;
}

// Per-frame voicing decision, one entry per f0Hz frame. Accepted by the
// `voiced` argument and by PitchCorrectOptions.voiced.
type VoicedFlags =
  | Int32Array
  | Uint8Array
  | Float32Array
  | readonly number[]
  | readonly boolean[];

interface MasteringAssistantSuggestStereoRequest {
  left: Float32Array;
  right: Float32Array;
  sampleRate?: number;
  params?: Record<string, number | boolean>;
}

// Same fields; a distinct name for the profile entry point.
interface MasteringAudioProfileStereoRequest extends MasteringAssistantSuggestStereoRequest {}

interface MasteringStreamingPreviewStereoRequest {
  left: Float32Array;
  right: Float32Array;
  sampleRate?: number;
  platforms?: StreamingPlatform[];
}

interface MeteringStereoRequest {
  left: Float32Array;
  right: Float32Array;
  sampleRate?: number;
  validate?: boolean;
}

ネイティブパッケージは、オプション、コールバック、ストリーミングスナップショット、リアルタイムエンジンメッセージ用の TypeScript 補助型もエクスポートしています。アプリ側で同じ構造を再定義せず、これらの型名を使ってください。

分野エクスポートされる型
解析オプション/結果AnalysisProgressCallback, BpmCandidate, ChordChromaMethod, KeyMode, KeyProfile, MelodyPoint, SectionTypeOrdinal, TempogramMode, TrimSilenceMode
ストリーミング解析StreamAnalyzerConfig, StreamAnalyzerStats, StreamFramesSoa, StreamProgressiveEstimate, StreamChordChange, StreamBarChord, StreamPatternScore
マスタリングとメータリングMasteringPreset, SoloProcessor, StreamingPlatform, DynamicsProcessorResult, CompressorDetector, DecrackleMode, DenoiseClassicalMode, DenoiseClassicalNoiseEstimator, EqBandInput, EqPhaseMode, EqSpectrumSnapshot, NormalizeMode
ステレオのマスタリング/メータリングのリクエストMasteringAssistantSuggestStereoRequest, MasteringAudioProfileStereoRequest, MasteringStreamingPreviewStereoRequest, MeteringStereoRequest
ピッチ補正PitchCorrectOptions, VoicedFlags
ミキシングAutomationCurve, GoniometerPoint, MeterTap, MixMeterSnapshot, MixResult, MixerProcessResult, PanLaw, PanLawName, PanLawInput, PanMode, SendTiming
リアルタイム音声VoicePresetId, VoicePresetCategory, RealtimeVoiceChangerPresetMetadata, RealtimeVoiceChangerPreset, RealtimeVoiceChangerConfigInput, RealtimeVoiceChangerConfig, RealtimeVoiceChangerOptions
リアルタイムエンジングラフEngineGraphSpec, EngineGraphNode, EngineGraphNodeType, EngineGraphConnection, EngineGraphMix, EngineGraphParameterBinding, EngineParameterInfo
リアルタイムエンジントランスポートEngineTransportState, EngineMarker, EngineClip, EngineAutomationPoint, EngineAutomationPointCurve, EngineMetronomeConfig, EngineTrackMonitorMode
プロジェクトのメタデータ/オートメーションProjectAssistSidecar, ProjectAssistSidecarInput, ProjectAutomationTargetKind, ProjectAutomationLaneDesc
リアルタイムエンジンのジョブ/テレメトリEngineBounceOptions, EngineBounceResult, EngineFreezeOptions, EngineFreezeResult, EngineCaptureStatus, EngineTelemetry, EngineTelemetryType, EngineTelemetryError, EngineMeterTelemetry