soundfile (PySoundFile)

0.13.1 · active · verified Sun Apr 05

The `soundfile` module (also known as PySoundFile) is a Python library for reading and writing sound files, built upon the C library `libsndfile`, CFFI, and NumPy. It provides a simple, high-level interface to handle various audio formats as NumPy arrays, making it ideal for audio processing and scientific applications. It is actively maintained with regular releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to generate a simple sine wave using NumPy, write it to a WAV file using `soundfile.write()`, and then read it back using `soundfile.read()`.

import soundfile as sf
import numpy as np
import os

# Create dummy audio data (mono, 44.1 kHz)
samplerate = 44100  # samples per second
duration = 1.0     # seconds
f_hz = 440         # sine wave frequency
t = np.linspace(0., duration, int(samplerate * duration), endpoint=False)
data = 0.5 * np.sin(2 * np.pi * f_hz * t)

output_filename = 'dummy_audio.wav'

# Write the audio data to a WAV file
sf.write(output_filename, data, samplerate)
print(f"Audio written to {output_filename}")

# Read the audio data back from the file
read_data, read_samplerate = sf.read(output_filename)
print(f"Audio read from {output_filename} with sample rate {read_samplerate}")
print(f"Read data shape: {read_data.shape}")

# Verify data
assert np.allclose(data, read_data[:len(data)])
assert samplerate == read_samplerate

# Clean up the dummy file
os.remove(output_filename)
print(f"Cleaned up {output_filename}")

view raw JSON →