High-quality Audio Sample Rate Conversion
Samplerate is a Python wrapper for Erik de Castro Lopo's `libsamplerate` (also known as Secret Rabbit Code), providing high-quality sample rate conversion for audio data in NumPy arrays. It implements all three APIs available in `libsamplerate`: Simple API, Full API, and Callback API. The library is currently at version 0.2.4 and maintains an active development status with regular releases.
Warnings
- gotcha When installing on Linux, the underlying `libsamplerate` C library may need to be installed separately (e.g., `libsamplerate0` on Debian/Ubuntu, `libsamplerate` on Arch Linux). Binary wheels for macOS and Windows include `libsamplerate` statically built.
- gotcha The `input_data` must be of `float32` dtype and C-contiguous for optimal performance and correct interaction with the underlying C library.
- gotcha There is an older, distinct package named `scikits.samplerate` which also provides audio resampling. While the `resample` function signature is compatible, `scikits.samplerate` only implements the Simple API and uses Cython, whereas `samplerate` (this package) uses `pybind11` and exposes all three libsamplerate APIs.
Install
-
pip install samplerate
Imports
- samplerate
import samplerate
Quickstart
import numpy as np
import samplerate
# Synthesize data
fs = 1000.0
t = np.arange(fs * 2) / fs
input_data = np.sin(2 * np.pi * 5 * t).astype(np.float32)
# Simple API
ratio = 1.5
converter = 'sinc_best'
output_data_simple = samplerate.resample(input_data, ratio, converter)
print(f"Original shape: {input_data.shape}, Resampled shape (Simple API): {output_data_simple.shape}")
# Full API
resampler = samplerate.Resampler(converter, channels=1)
output_data_full = resampler.process(input_data, ratio, end_of_input=True)
print(f"Resampled shape (Full API): {output_data_full.shape}")
assert np.allclose(output_data_simple, output_data_full)