0
# SoundFile
1
2
A comprehensive Python audio library that enables reading and writing of various sound file formats through libsndfile, CFFI, and NumPy integration. SoundFile provides block-wise audio processing, metadata handling, and virtual I/O operations, with audio data represented as NumPy arrays for efficient manipulation.
3
4
## Package Information
5
6
- **Package Name**: soundfile
7
- **Language**: Python
8
- **Installation**: `pip install soundfile`
9
- **Dependencies**: `cffi>=1.0`, `numpy`
10
11
## Core Imports
12
13
```python
14
import soundfile
15
```
16
17
Common usage patterns:
18
19
```python
20
import soundfile as sf
21
from soundfile import read, write, SoundFile
22
```
23
24
## Basic Usage
25
26
```python
27
import soundfile as sf
28
import numpy as np
29
30
# Read an audio file
31
data, samplerate = sf.read('input.wav')
32
print(f'Audio shape: {data.shape}, Sample rate: {samplerate}')
33
34
# Write audio data to a file
35
sf.write('output.wav', data, samplerate)
36
37
# Read only a portion of a file
38
data, samplerate = sf.read('input.wav', start=1000, stop=2000)
39
40
# Block-wise reading for large files
41
for block in sf.blocks('large_file.wav', blocksize=1024):
42
# Process each block
43
processed = block * 0.5 # Example: reduce volume
44
```
45
46
## Architecture
47
48
SoundFile provides a flexible, NumPy-based API for audio I/O:
49
50
- **Functional Interface**: Simple read/write functions for quick operations
51
- **Object Interface**: `SoundFile` class for advanced file handling with context manager support
52
- **Block Processing**: Generator-based block reading for memory-efficient processing of large files
53
- **Format Support**: Extensive format and subtype support through libsndfile
54
- **Metadata Handling**: Read and write audio file metadata (title, artist, etc.)
55
56
## Capabilities
57
58
### Core I/O Functions
59
60
Primary functions for reading and writing audio files, supporting all major audio formats with NumPy array data representation.
61
62
```python { .api }
63
def read(file, frames=-1, start=0, stop=None, dtype='float64', always_2d=False,
64
fill_value=None, out=None, samplerate=None, channels=None,
65
format=None, subtype=None, endian=None, closefd=True):
66
"""
67
Read audio data from a sound file.
68
69
Returns: tuple (audiodata: ndarray, samplerate: int)
70
"""
71
72
def write(file, data, samplerate, subtype=None, endian=None, format=None,
73
closefd=True, compression_level=None, bitrate_mode=None):
74
"""Write audio data to a sound file."""
75
76
def blocks(file, blocksize=None, overlap=0, frames=-1, start=0, stop=None,
77
dtype='float64', always_2d=False, fill_value=None, out=None,
78
samplerate=None, channels=None, format=None, subtype=None,
79
endian=None, closefd=True):
80
"""Return a generator for block-wise reading of audio data."""
81
```
82
83
[Core I/O Functions](./core-io.md)
84
85
### SoundFile Class
86
87
Object-oriented interface for advanced audio file handling with context manager support, seek operations, and metadata access.
88
89
```python { .api }
90
class SoundFile:
91
def __init__(self, file, mode='r', samplerate=None, channels=None,
92
subtype=None, endian=None, format=None, closefd=True,
93
compression_level=None, bitrate_mode=None): ...
94
95
def read(self, frames=-1, dtype='float64', always_2d=False,
96
fill_value=None, out=None): ...
97
def write(self, data): ...
98
def seek(self, frames, whence=0): ...
99
def tell(self): ...
100
101
# Properties
102
samplerate: int
103
frames: int
104
channels: int
105
format: str
106
subtype: str
107
```
108
109
[SoundFile Class](./soundfile-class.md)
110
111
### File Information and Format Support
112
113
Utilities for querying file information, available formats, and format validation.
114
115
```python { .api }
116
def info(file, verbose=False):
117
"""Returns an object with information about a sound file."""
118
119
def available_formats():
120
"""Return a dictionary of available major formats."""
121
122
def available_subtypes(format=None):
123
"""Return a dictionary of available subtypes."""
124
125
def check_format(format, subtype=None, endian=None):
126
"""Check if the combination of format/subtype/endian is valid."""
127
128
def default_subtype(format):
129
"""Return the default subtype for a given format."""
130
```
131
132
[File Information](./file-info.md)
133
134
## Constants and Types
135
136
### Version Information
137
138
```python { .api }
139
__version__: str # Module version
140
__libsndfile_version__: str # libsndfile version
141
```
142
143
### Seek Constants
144
145
```python { .api }
146
SEEK_SET: int # Seek from beginning
147
SEEK_CUR: int # Seek from current position
148
SEEK_END: int # Seek from end
149
```
150
151
### Exception Classes
152
153
```python { .api }
154
class SoundFileError(Exception):
155
"""Base class for soundfile-specific errors."""
156
157
class SoundFileRuntimeError(SoundFileError, RuntimeError):
158
"""Runtime error in soundfile module."""
159
160
class LibsndfileError(SoundFileRuntimeError):
161
"""libsndfile errors with error code and message."""
162
code: int
163
prefix: str
164
error_string: str
165
```