@audio/stretch

中文文档
2.3.0发布于 2026/10/18MITTypeScriptES Module近 30 天下载 2427

Time stretching — umbrella for @audio/stretch-* atoms (WSOLA, phase vocoder variants, PaulStretch, PSOLA, SMS)

原始使用文档
文档目录18 节
  1. Usage
  2. Time domain
  3. wsola — @audio/stretch-wsola
  4. psola — @audio/stretch-psola
  5. Frequency domain
  6. pvoc — @audio/stretch-pvoc
  7. pvoc-lock — @audio/stretch-pvoc-lock
  8. pvsola — @audio/stretch-pvsola
  9. pghi — @audio/stretch-pghi
  10. transient — @audio/stretch-transient
  11. hybrid — @audio/stretch-hybrid
  12. paulstretch — @audio/stretch-paulstretch
  13. Sinusoidal
  14. sms — @audio/stretch-sms
  15. Quality metrics — @audio/quality
  16. Research & comparison
  17. See also
  18. References

@audio/stretch test npm license

Try it in the browser: Pitch and tempo changer. Runs on this package, nothing is uploaded.

Time stretching algorithms — umbrella over @audio/stretch-* atoms.

AtomAlgorithmDomainQualityCPUBest for
@audio/stretch-wsolaWSOLAtime★★★★lowspeech, solo voice
@audio/stretch-psolaPSOLAtime★★★★mediumspeech, monophonic instruments
@audio/stretch-pvocplain phase vocoderfreq★★mediumeducational baseline
@audio/stretch-pvoc-lockphase-locked vocoderfreq★★★★mediumgeneral music
@audio/stretch-pghiphase-gradient vocoderfreq★★★★mediumvibrato, glides, chirps
@audio/stretch-pvsolavocoder reset to the waveformfreq+time★★★★★mediumslowing speech, solo voice
@audio/stretch-transienttransient-aware vocoderfreq★★★★★mediummusic with percussion
@audio/stretch-hybridHPSS hybridfreq+time★★★★highfull mixes — drums over tonal
@audio/stretch-paulstretchPaulStretchfreq—mediumextreme stretch (ambient, drones)
@audio/stretch-smsSinusoidal Modelingsinusoidal★★★★highharmonic / tonal material

For pitch shifting, see the @audio/shift-* family.

Usage

Install the umbrella (all atoms):

npm install @audio/stretch
import { transient, wsola } from '@audio/stretch'

let slower = transient(samples, { factor: 2 })          // 2× slower, same pitch
let fast   = wsola(samples, { factor: 0.75 })           // 1.33× faster

let write = transient({ factor: 1.5 })                  // real-time streaming
write(block1)
write(block2)
write()                                                  // → remaining samples

Or install just the atom you need — each is self-contained:

npm install @audio/stretch-transient
import transient from '@audio/stretch-transient'
let out = transient(samples, { factor: 2 })

Float32Array in/out; a channel array [L, R] (or Float64Array) is accepted and processed per channel — parity with @audio/shift. Output sizes may be variable — small or empty early chunks are normal in streaming.

Time domain

wsola — @audio/stretch-wsola

Waveform Similarity Overlap-Add, in the segment form of SoundTouch and sox tempo. Segments of the input are laid one hop apart, each crossfaded into the one before, and each read where its head best continues the one before (normalized cross-correlation within ±delta of where the time map puts it). The waveform is copied, not resynthesized, so a voice keeps its glottal pulse shape and its consonants keep their attacks. A phase vocoder keeps each harmonic but not their alignment to one another, which is why speech through it sounds distant. Channels share one search. No FFT.

import wsola from '@audio/stretch-wsola'

wsola(data, { factor: 1.5 })
wsola([left, right], { factor: 0.5, sampleRate: 48000 })
ParamDefault
factor1Time stretch ratio, or a function of input seconds
sampleRate44100
frameSize40 msSegment
hopSizeframeSize · 3/5Output hop; segments cross over the rest (16 ms, one period at 62.5 Hz)
delta8 msSearch (±), half that period

Use when: shortening speech, a solo voice or a monophonic instrument; slowing them, pvsola (copying repeats noise and reverberation into a flanger).
Not for: chords and mixes. One alignment cannot fit several pitches; use the frequency-domain methods.

psola — @audio/stretch-psola

Pitch-Synchronous Overlap-Add. Detects pitch period via autocorrelation, then windows grains at pitch cycle boundaries. Because grains align with the pitch cycle there are no phase discontinuities at overlaps — cleaner than WSOLA for monophonic pitched signals.

import psola from '@audio/stretch-psola'

psola(data, { factor: 1.5 })
psola(data, { factor: 0.75, sampleRate: 48000 })
psola(data, { factor: 2, minFreq: 100, maxFreq: 400 })  // male voice range
ParamDefault
factor1Time stretch ratio
sampleRate44100For pitch detection frequency range
minFreq80Lowest expected pitch (Hz)
maxFreq500Highest expected pitch (Hz)

Use when: Speech, solo vocals, monophonic instruments, factors 0.5–2×.
Not for: Polyphonic material — autocorrelation finds one pitch period so chords get mangled. Extreme ratios (>2×) cause gaps.

Frequency domain

pvoc — @audio/stretch-pvoc

Plain phase vocoder. Each bin's phase advances at its instantaneous frequency independently. Magnitudes are preserved but incoherent inter-harmonic phase relationships give complex signals a diffuse, "underwater" quality.

import pvoc from '@audio/stretch-pvoc'
pvoc(data, { factor: 2 })
ParamDefault
factor1Time stretch ratio
frameSize2048FFT size (power of 2)
hopSizeframeSize/4Hop between frames

Use when: Educational baseline, simple tonal signals.
Not for: General music — use pvoc-lock or transient.

pvoc-lock — @audio/stretch-pvoc-lock

Phase-locked vocoder (Laroche & Dolson, 1999). After propagating phases, locks non-peak bins to their nearest spectral peak's rotation. Restores harmonic phase coherence, eliminating phasiness.

import pvocLock from '@audio/stretch-pvoc-lock'
pvocLock(data, { factor: 2 })

Same options as pvoc.

Use when: General music — tonal/ambient material where transient resets aren't needed.
Not for: Percussive material where attacks matter — use transient.

pvsola — @audio/stretch-pvsola

A phase-locked vocoder whose frames restart from the input's own waveform wherever it fits (Moinet & Dutoit, DAFx 2011). Where a voice is periodic its frames take the input's own phases and keep the shape of its glottal pulses; noise, breath and reverberation stay the vocoder's, so slowing never repeats them (WSOLA's flanger) nor spreads the voice (the vocoder's phasiness).

import pvsola from '@audio/stretch-pvsola'
pvsola(data, { factor: 1.5 })
ParamDefault
factor1Time stretch ratio, or a function of input seconds
sampleRate44100
frameSize46 msFrame, a power of 2
shift4.5 msShift searched for a reset (±)

Use when: slowing speech or a solo voice.
Not for: shortening, where wsola keeps attacks better.

pghi — @audio/stretch-pghi

Phase Gradient Heap Integration — "Phase Vocoder Done Right" (Průša & Holighaus, 2017). Synthesis phase is integrated from the analysis phase gradients, visiting bins in magnitude order via a max-heap: no peak picking, no transient heuristics; chirps, vibrato and glides stay coherent by construction.

import pghi from '@audio/stretch-pghi'

pghi(data, { factor: 2 })
ParamDefault
factor1Time stretch ratio
frameSize2048FFT size (power of 2)
hopSizeframeSize/8Hop — gradient integration wants dense frames
tolerance1e-6Bins below tolerance×max get random phase

Use when: modulated material — vibrato, glissandi, pitch-unstable sources.
Not for: steady polyphony — pvoc-lock's identity locking reproduces intra-partial phases exactly where gradient integration only approximates them.

transient — @audio/stretch-transient

Transient-aware phase-locked vocoder (Röbel, 2003). Measures spectral flux between frames; on a sharp onset it resets to the original analysis phase instead of propagating it, preserving attack sharpness on drums and plucks. Implies phase locking.

import transient from '@audio/stretch-transient'

transient(data, { factor: 2 })
transient(data, { factor: 1.5, transientThreshold: 2.0 })  // less sensitive detection
ParamDefault
factor1Time stretch ratio
frameSize2048FFT size (power of 2)
hopSizeframeSize/4Hop between frames
transientThreshold1.5Spectral flux threshold (higher = fewer resets)

Use when: The right default for most music — percussion, mixed sources.
Not for: Voice/speech — use psola. Extreme stretch — use paulstretch.

hybrid — @audio/stretch-hybrid

Harmonic/percussive hybrid (Driedger & Müller). Median-filter HPSS splits the spectrogram into two layers; the harmonic layer goes through the phase-locked vocoder, the percussive layer through short-frame OLA — chords stay coherent and attacks stay sharp, where one algorithm must trade one for the other.

import hybrid from '@audio/stretch-hybrid'

hybrid(data, { factor: 2 })
ParamDefault
factor1Time stretch ratio
frameSize2048FFT size for HPSS + harmonic path
percFrame512OLA frame for the percussive layer
harmMedian17Median filter across time (frames)
percMedian17Median filter across frequency (bins)

Use when: full mixes — drums over tonal material.
Cost: separation + two stretches ≈ 4–6× the CPU of pvoc-lock alone.

paulstretch — @audio/stretch-paulstretch

Extreme time stretching via phase randomization (Nasca, 2006). Preserves magnitudes but replaces all phases with random values, producing smooth, dreamlike textures. Designed for large factors.

import paulstretch from '@audio/stretch-paulstretch'

paulstretch(data, { factor: 8 })
paulstretch(data, { factor: 100, frameSize: 8192 })
ParamDefault
factor8Time stretch ratio (best >2×)
frameSize4096FFT size (larger = smoother)
seed0x1f123bb5PRNG seed (deterministic output)

Use when: Ambient music, sound design, drone generation, 8×–1000× stretch.
Not for: Small ratios (<2×) — sounds washed out. Not for preserving rhythm or transients.

Sinusoidal

sms — @audio/stretch-sms

Sinusoidal Modeling Synthesis (Serra 1989, McAulay-Quatieri 1986). Decomposes audio into individually tracked sinusoidal partials and resynthesizes at the new time rate. Each partial's frequency and magnitude are interpolated independently — no phase spreading or bin-by-bin artifacts.

import sms from '@audio/stretch-sms'

sms(data, { factor: 2 })
sms(data, { factor: 0.5, maxTracks: 80 })
sms(data, { factor: 3, frameSize: 4096 })
ParamDefault
factor1Time stretch ratio
frameSize2048FFT frame size
hopSizeframeSize/4Hop between frames
maxTracks60Max simultaneous sinusoidal tracks
minMag1e-4Peak detection threshold (linear)
freqDev3Max frequency deviation (bins) for track continuation
residualMix1Stochastic residual blended into the sinusoidal output

Use when: Harmonic / tonal content — instruments, chords, vocals — where the phase vocoder introduces smearing. Default residualMix=1 blends breath, noise, and transient energy alongside the sinusoidal model.
Not for: Noise-dominated material.

Quality metrics — @audio/quality

Every atom is self-contained (framing/OLA helpers inlined; the phase-locking engine lives in @audio/spectral-pvoc). Output quality is evaluated with @audio/quality:

import { lsd, spectralSim, chordBalance, chordRetention, modulationDepth } from '@audio/quality'

lsd (log-spectral distance), spectralSim (cosine similarity), chordBalance, chordRetention, and modulationDepth (AM depth per partial) evaluate algorithm output against a reference.

Research & comparison

CommandWhat it does
node scripts/compare.jswrites compare.html — interactive waveforms, playback, internal-vs-external comparisons
node scripts/bench.jsthroughput and ×realtime numbers for batch and streaming
node scripts/diagnose.jstargeted diagnostics for specific algorithm behaviors

Demo for a lightweight browser listening matrix.

See also

References

  • Verhelst, W. & Roelands, M. (1993). "An overlap-add technique based on waveform similarity (WSOLA)." ICASSP.
  • Laroche, J. & Dolson, M. (1999). "Improved phase vocoder time-scale modification of audio." IEEE Trans. Speech Audio Processing.
  • Röbel, A. (2003). "A new approach to transient processing in the phase vocoder." DAFx.
  • Nasca, P. (2006). "PaulStretch — extreme time stretching." paulnasca.com.
  • Moulines, E. & Charpentier, F. (1990). "Pitch-synchronous waveform processing techniques for text-to-speech synthesis using diphones." Speech Communication, 9(5-6).
  • Driedger, J. & Müller, M. (2016). "A review of time-scale modification of music signals." Applied Sciences, 6(2).
  • Serra, X. (1989). "A System for Sound Analysis/Transformation/Synthesis Based on a Deterministic plus Stochastic Decomposition." PhD thesis, Stanford.
  • McAulay, R.J. & Quatieri, T.F. (1986). "Speech analysis/synthesis based on a sinusoidal representation." IEEE Trans. ASSP, 34(4).

版本与发布记录

@audio/stretch 共发布 9 个版本,首次发布于 2026/07/09;过去 12 个月发布了 9 个版本。

版本发布日期距今
2.3.0latest2026/10/1820 天前
2.2.02026/10/031 个月前
2.1.02026/09/291 个月前
2.0.52026/08/292 个月前
2.0.42026/07/113 个月前
2.0.32026/07/113 个月前

关于 @audio/stretch 的常见问题

@audio/stretch 是什么?

Time stretching — umbrella for @audio/stretch-* atoms (WSOLA, phase vocoder variants, PaulStretch, PSOLA, SMS)

如何安装 @audio/stretch?

在项目目录运行 npm install @audio/stretch,或使用 pnpm add / yarn add / bun add。

@audio/stretch 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@audio/stretch 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@audio/stretch 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=18。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@audio/stretch 可以商用吗?

@audio/stretch 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@audio/stretch 的下载量有多少?

根据 npm 官方下载统计,@audio/stretch 在 2026/10/07 – 2026/11/05 这 30 天内被下载 2,427 次,日均约 81 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@audio/stretch 还在维护吗?

最新版本 2.3.0 发布于 2026/10/18(20 天前);至今共发布 9 个版本,其中过去 12 个月发布了 9 个;首次发布于 2026/07/09。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。