Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python audio processing libraries read, write, and transform sound files and sample arrays. Most decode audio into a NumPy array of samples that analysis and resampling code can operate on. These libraries let speech pipelines, music apps, and machine learning models prepare audio for analysis.
Popularity
PyAV, whose count also covers video work, has the most monthly downloads in this comparison, at 52.3M.
def convert_audio(input_path: Path, output_path: Path, codec_name: str):
with (
av.open(input_path) as input_audio,
av.open(output_path, "w") as output_audio,
):
input_audio_stream = input_audio.streams.audio[0]
output_audio_stream = output_audio.add_stream(codec_name)
for frame in input_audio.decode(input_audio_stream):
for packet in output_audio_stream.encode(frame):
output_audio.mux(packet)
for packet in output_audio_stream.encode():
output_audio.mux(packet)
SoundFile
Reads and writes audio files.
Downloads / mo
35.5M
Stars
874
Last release
0.14.0
License
BSD-3-Clause
Runs on
libsndfile
Strengths
Reads and writes sound files.Use soundfile.read and soundfile.write for supported audio formats.
Processes audio in blocks.Read short overlapping blocks without loading the entire recording.
Limitations
Raw audio needs format details.Specify the sample rate, channel count, and subtype when opening headerless audio.
def __soundfile_load(path, offset, duration, dtype):
"""Load an audio buffer using soundfile."""
if isinstance(path, sf.SoundFile):
# If the user passed an existing soundfile object, # we can use it directly context = path
else:
# Otherwise, create the soundfile object context = sf.SoundFile(path)
with context as sf_desc:
sr_native = sf_desc.samplerate
if offset != 0:
if offset > 0:
# Seek to the start of the target read sf_desc.seek(int(offset * sr_native))
else:
sf_desc.seek(-int(abs(offset) * sr_native), whence=sf.SEEK_END)
if duration is not None:
frame_duration = int(duration * sr_native)
else:
frame_duration = -1
# Load the target number of frames, and transpose to match librosa form y = sf_desc.read(frames=frame_duration, dtype=dtype, always_2d=False).T
return y, sr_native
pydub
Represents audio with immutable AudioSegment objects.
Downloads / mo
17.2M
Stars
9.8K
Last release
0.25.1
License
MIT
Strengths
Slices clips by time.Select a section of audio using millisecond-based slices.
Mixes clips on a timeline.Overlay clips at a chosen position with background-gain control.
Limitations
Compressed formats need ffmpeg.Install ffmpeg to open or save formats such as MP3.
def add_audio_segment(
self,
new_segment: AudioSegment,
time: float | None = None,
gain_to_background: float | None = None,
):
"""
This method adds an audio segment from an
AudioSegment type object and suitable parameters.
Parameters
---------- new_segment
The audio segment to add
time
the timestamp at which the
sound should be added.
gain_to_background
The gain of the segment from the background.
"""
if not self.includes_sound:
self.includes_sound = True
self.create_audio_segment()
segment = self.audio_segment
curr_end = segment.duration_seconds
if time is None:
time = curr_end
if time < 0:
raise ValueError("Adding sound at timestamp < 0")
new_end = time + new_segment.duration_seconds
diff = new_end - curr_end
if diff > 0:
segment = segment.append(
AudioSegment.silent(int(np.ceil(diff * 1000))),
crossfade=0,
)
self.audio_segment = segment.overlay(
new_segment,
position=int(1000 * time),
gain_during_overlay=gain_to_background,
)
Python-SoXR
Converts one-dimensional audio between sample rates.
def load_audio(file: str, sr: int = SAMPLE_RATE):
"""
Open an audio file and read as mono waveform, resampling as necessary
Parameters
---------- file: str
The audio file to open
sr: int
The sample rate to resample the audio if necessary
Returns
------- A NumPy array containing the audio waveform, in float32 dtype.
"""
try:
# This launches a subprocess to decode audio while down-mixing and resampling as necessary. # Requires the ffmpeg CLI and `ffmpeg-python` package to be installed. out, _ = (
ffmpeg.input(file, threads=0)
.output("-", format="s16le", acodec="pcm_s16le", ac=1, ar=sr)
.run(cmd=["ffmpeg", "-nostdin"], capture_stdout=True, capture_stderr=True)
)
except ffmpeg.Error as e:
raise RuntimeError(f"Failed to load audio: {e.stderr.decode()}") from e
return np.frombuffer(out, np.int16).flatten().astype(np.float32) / 32768.0
librosa
Provides algorithms for audio and music signal processing.
Downloads / mo
11.1M
Stars
9.0K
Last release
1.0.1
License
ISC
Strengths
Analyzes rhythm and onset strength.Estimate beat positions and build onset-strength features from audio.
Loads audio for analysis.Decode audio into a floating-point waveform.
Limitations
Loading resamples audio by default.Pass sr=None to keep the file’s original sample rate.
Loading mixes channels by default.Pass mono=False when each input channel must stay separate.
def audioread_info(path: Pathlike) -> LibsndfileCompatibleAudioInfo:
"""
Return an audio info data structure that's a compatible subset of ``pysoundfile.info()``
that we need to create a ``Recording`` manifest.
"""
import audioread
# We just read the file and compute the number of samples # -- no other method seems fully reliable... with audioread.audio_open(
str(path), backends=_available_audioread_backends()
) as input_file:
shape = audioread_load(input_file)[0].shape
if len(shape) == 1:
num_samples = shape[0]
else:
num_samples = shape[1]
return LibsndfileCompatibleAudioInfo(
channels=input_file.channels,
frames=num_samples,
samplerate=int(input_file.samplerate),
duration=num_samples / input_file.samplerate,
)
TorchAudio
Provides audio processing tools for the PyTorch ecosystem.
Downloads / mo
5.8M
Stars
3.0K
Last release
2.11.1
License
BSD-2-Clause
Runs on
PyTorch
Strengths
Resamples PyTorch waveforms.Resample waveform tensors through functional or reusable transform APIs.
Runs resampling on GPUs.Use tensor convolution to resample audio on compatible GPU hardware.
Limitations
Audio decoding needs TorchCodec.Install TorchCodec for load and save, or use its classes directly.
@staticmethod
def resample_audio(
audio: dict[str, Any],
*,
target_sampling_rate: int,
max_samples: int | None = None,
) -> np.typing.NDArray[np.floating]:
"""Resample an audio input to a target sampling rate and optionally truncate to a maximum number of samples.
Args:
audio: A list of dictionaries containing audio data under the "audio" key, where each audio is a dictionary with "array" and "sampling_rate" keys.
target_sampling_rate: The sampling rate to resample the audio to.
max_samples: The maximum number of samples to keep for each audio. If None, no truncation is applied.
"""
import torchaudio
audio = audio["audio"]
if audio["sampling_rate"] != target_sampling_rate:
logger.debug(
f"Resampling audio from {audio['sampling_rate']} Hz to {target_sampling_rate} Hz."
)
resampler = torchaudio.transforms.Resample(
orig_freq=audio["sampling_rate"],
new_freq=target_sampling_rate,
)
audio_array = resampler(torch.from_numpy(audio["array"]).float()).numpy()
else:
audio_array = audio["array"]
# Convert to mono if needed if audio_array.ndim > 1 and audio_array.shape[0] > 1:
audio_array = np.mean(audio_array, axis=0)
if max_samples is not None:
num_samples = audio_array.shape[-1]
if num_samples > max_samples:
audio_array = audio_array[..., :max_samples]
audio_array = cast(
"np.ndarray[tuple[Any, ...], np.dtype[np.floating[Any]]]",
audio_array,
)
return audio_array
FAQ
SoundFile suits reading and writing audio files as NumPy arrays. librosa suits music and audio analysis. pydub suits slicing, joining, and converting audio clips.
librosa provides algorithms for audio and music signal processing, such as spectrograms, beat tracking, and pitch features.
pydub represents audio as immutable AudioSegment objects that support slicing, concatenation, and format conversion. It uses FFmpeg to read formats other than WAV.
TorchAudio provides audio loading, transforms, and models for PyTorch. Its transforms run on tensors inside training pipelines.
ffmpeg-python builds FFmpeg command lines with filter graphs from Python. PyAV binds the FFmpeg libraries directly for frame-level access.
For coding agents
Found your audio processing library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.