or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# audioread

1

2

A cross-platform audio file decoding library that provides a unified interface for reading various audio formats. It automatically selects from multiple available backends (GStreamer, Core Audio, MAD, FFmpeg/Libav, standard library) to decode audio files, providing transparent cross-platform compatibility without requiring specific audio library dependencies.

3

4

## Package Information

5

6

- **Package Name**: audioread

7

- **Package Type**: pypi

8

- **Language**: Python

9

- **Installation**: `pip install audioread`

10

- **Requires**: Python 3.6+

11

12

## Core Imports

13

14

```python

15

import audioread

16

```

17

18

Import specific components:

19

20

```python

21

from audioread import audio_open, available_backends, DecodeError, NoBackendError

22

from audioread import AudioFile # Base class

23

```

24

25

Access version information:

26

27

```python

28

import audioread

29

print(audioread.__version__) # Package version

30

```

31

32

## Basic Usage

33

34

```python

35

import audioread

36

37

# Open and read an audio file

38

with audioread.audio_open('song.mp3') as f:

39

print(f"Channels: {f.channels}")

40

print(f"Sample rate: {f.samplerate} Hz")

41

print(f"Duration: {f.duration} seconds")

42

43

# Read raw PCM data

44

for buffer in f:

45

# Process 16-bit little-endian signed integer PCM data

46

process_audio_data(buffer)

47

48

# Check available backends on the system

49

backends = audioread.available_backends()

50

print(f"Available backends: {[b.__name__ for b in backends]}")

51

52

# Use specific backends

53

with audioread.audio_open('song.mp3', backends=backends) as f:

54

# Process with specified backends only

55

pass

56

```

57

58

## Architecture

59

60

audioread uses a pluggable backend architecture that automatically selects the best available decoder:

61

62

- **Backend Selection**: Tries each available backend until one successfully opens the file

63

- **Unified Interface**: All backends implement the same AudioFile interface

64

- **Cross-platform**: Different backends available on different platforms (Core Audio on macOS, GStreamer on Linux, etc.)

65

- **Fallback Chain**: Multiple backends provide redundancy and format support

66

67

Available backends include:

68

- **RawAudioFile**: Standard library support for WAV, AIFF, Au files

69

- **FFmpegAudioFile**: Command-line FFmpeg/avconv support for most formats

70

- **GstAudioFile**: GStreamer support (Linux/cross-platform)

71

- **ExtAudioFile**: CoreAudio support (macOS)

72

- **MadAudioFile**: MAD library support for MPEG audio

73

74

## Capabilities

75

76

### Audio File Opening

77

78

Open audio files with automatic backend selection and unified interface.

79

80

```python { .api }

81

def audio_open(path, backends=None):

82

"""

83

Open an audio file using a library that is available on this system.

84

85

Parameters:

86

- path: str, path to the audio file

87

- backends: list, optional list of backend classes to try (default: all available)

88

89

Returns:

90

AudioFile instance with channels, samplerate, duration properties

91

92

Raises:

93

NoBackendError: if all backends fail to read the file

94

IOError: if file doesn't exist

95

"""

96

```

97

98

### Backend Discovery

99

100

Query available audio decoding backends on the current system.

101

102

```python { .api }

103

def available_backends(flush_cache=False):

104

"""

105

Returns a list of backends that are available on this system.

106

107

Parameters:

108

- flush_cache: bool, if True, flush cache and reconstruct backend list

109

110

Returns:

111

List of backend classes that can be used for decoding

112

"""

113

```

114

115

### Audio File Interface

116

117

Base interface provided by all audio file objects returned from audio_open(). Note that specific backends may have variations in method signatures.

118

119

```python { .api }

120

class AudioFile:

121

"""Base class for all audio file types."""

122

123

@property

124

def channels(self):

125

"""Number of audio channels (int)."""

126

127

@property

128

def samplerate(self):

129

"""Sample rate in Hz (int)."""

130

131

@property

132

def duration(self):

133

"""Length of the audio in seconds (float)."""

134

135

def close(self):

136

"""Close the underlying file."""

137

138

def __enter__(self):

139

"""Context manager entry."""

140

141

def __exit__(self, exc_type, exc_val, exc_tb):

142

"""Context manager exit."""

143

144

def __iter__(self):

145

"""Iterator support - yields blocks of PCM data."""

146

```

147

148

### Backend Classes

149

150

Specific backend implementations (normally not used directly). Each backend has its own specific methods and parameters.

151

152

```python { .api }

153

class RawAudioFile(AudioFile):

154

"""AIFF, WAV, or Au file reader using standard library."""

155

156

def __init__(self, filename: str):

157

"""Open file with standard library modules."""

158

159

def read_data(self, block_samples: int = 1024):

160

"""Read audio data in blocks."""

161

162

class FFmpegAudioFile(AudioFile):

163

"""Audio file decoder using FFmpeg command-line tool."""

164

165

def __init__(self, filename: str, block_size: int = 8192):

166

"""Open file with FFmpeg/avconv."""

167

168

def read_data(self, timeout: float = 10.0):

169

"""Read audio data with timeout."""

170

171

class GstAudioFile(AudioFile):

172

"""Audio file decoder using GStreamer."""

173

174

def __init__(self, filename: str):

175

"""Open file with GStreamer."""

176

177

class ExtAudioFile(AudioFile):

178

"""Audio file decoder using Core Audio on macOS."""

179

180

def __init__(self, filename: str):

181

"""Open file with CoreAudio."""

182

183

@property

184

def nframes(self):

185

"""Number of frames in source file."""

186

187

def setup(self, bitdepth: int = 16):

188

"""Set client format parameters."""

189

190

class MadAudioFile(AudioFile):

191

"""MPEG audio file decoder using MAD library."""

192

193

def __init__(self, filename: str):

194

"""Open file with MAD/pymad."""

195

196

def read_blocks(self, block_size: int = 4096):

197

"""Read audio data in blocks."""

198

```

199

200

### Exception Handling

201

202

Exception types raised by audioread operations.

203

204

```python { .api }

205

class DecodeError(Exception):

206

"""Base exception class for all decoding errors."""

207

208

class NoBackendError(DecodeError):

209

"""

210

The file could not be decoded by any backend.

211

Either no backends are available or each available backend failed.

212

"""

213

```

214

215

### Backend-Specific Exceptions

216

217

Additional exceptions that may be raised by specific backends.

218

219

```python { .api }

220

# Raw backend (rawread module)

221

class UnsupportedError(DecodeError):

222

"""File is not an AIFF, WAV, or Au file."""

223

224

class BitWidthError(DecodeError):

225

"""The file uses an unsupported bit width."""

226

227

# FFmpeg backend (ffdec module)

228

class FFmpegError(DecodeError):

229

"""Base FFmpeg error."""

230

231

class UnsupportedError(FFmpegError):

232

"""File could not be decoded by FFmpeg."""

233

234

class CommunicationError(FFmpegError):

235

"""Raised when the output of FFmpeg is not parseable."""

236

237

class NotInstalledError(FFmpegError):

238

"""Could not find the ffmpeg binary."""

239

240

class ReadTimeoutError(FFmpegError):

241

"""Reading from the ffmpeg command-line tool timed out."""

242

243

# GStreamer backend (gstdec module)

244

class GStreamerError(DecodeError):

245

"""Base GStreamer error."""

246

247

class IncompleteGStreamerError(GStreamerError):

248

"""Missing GStreamer base plugins."""

249

250

class UnknownTypeError(GStreamerError):

251

"""Raised when Gstreamer can't decode the given file type."""

252

253

class FileReadError(GStreamerError):

254

"""Raised when the file can't be read at all."""

255

256

class NoStreamError(GStreamerError):

257

"""Raised when no audio streams were found."""

258

259

class MetadataMissingError(GStreamerError):

260

"""Raised when GStreamer fails to report stream metadata."""

261

262

# MAD backend (maddec module)

263

class UnsupportedError(DecodeError):

264

"""File not readable by MAD library."""

265

266

# macOS Core Audio backend (macca module)

267

class MacError(DecodeError):

268

"""macOS-specific Core Audio error."""

269

```

270

271

### Version Information and Module Variables

272

273

Access package version information and module-level variables.

274

275

```python { .api }

276

__version__: str # Package version string (e.g., "3.0.1")

277

278

BACKENDS: list # Cached list of available backend classes

279

280

# From version module

281

version: str # Full version string (e.g., "3.0.1")

282

short_version: str # Short version string (e.g., "3.0")

283

```

284

285

## Usage Examples

286

287

### Basic Audio File Processing

288

289

```python

290

import audioread

291

292

def analyze_audio_file(filepath):

293

try:

294

with audioread.audio_open(filepath) as f:

295

print(f"File: {filepath}")

296

print(f"Format: {f.channels} channels, {f.samplerate} Hz, {f.duration:.2f}s")

297

298

# Calculate total samples

299

total_samples = int(f.samplerate * f.duration * f.channels)

300

print(f"Total samples: {total_samples}")

301

302

# Read in chunks and calculate RMS

303

rms_values = []

304

for chunk in f:

305

# Convert bytes to 16-bit integers

306

import struct

307

samples = struct.unpack(f'<{len(chunk)//2}h', chunk)

308

rms = (sum(s*s for s in samples) / len(samples)) ** 0.5

309

rms_values.append(rms)

310

311

avg_rms = sum(rms_values) / len(rms_values)

312

print(f"Average RMS: {avg_rms:.2f}")

313

314

except audioread.NoBackendError:

315

print(f"No backend could decode {filepath}")

316

except IOError:

317

print(f"File not found: {filepath}")

318

```

319

320

### Converting Audio to WAV

321

322

```python

323

import audioread

324

import wave

325

326

def convert_to_wav(input_path, output_path):

327

"""Convert any supported audio format to WAV."""

328

with audioread.audio_open(input_path) as f:

329

with wave.open(output_path, 'wb') as wav_file:

330

wav_file.setnchannels(f.channels)

331

wav_file.setsampwidth(2) # 16-bit samples

332

wav_file.setframerate(f.samplerate)

333

334

for data in f:

335

wav_file.writeframes(data)

336

337

print(f"Converted {input_path} to {output_path}")

338

339

# Example usage

340

convert_to_wav('song.mp3', 'song.wav')

341

```

342

343

### Backend-Specific Usage

344

345

```python

346

import audioread

347

348

def try_specific_backends(filepath):

349

"""Try backends in preferred order."""

350

# Get all available backends

351

all_backends = audioread.available_backends()

352

353

# Try FFmpeg first if available

354

ffmpeg_backends = [b for b in all_backends if 'FFmpeg' in b.__name__]

355

if ffmpeg_backends:

356

try:

357

with audioread.audio_open(filepath, backends=ffmpeg_backends) as f:

358

print(f"Opened with FFmpeg backend: {f.duration:.2f}s")

359

return

360

except audioread.DecodeError:

361

pass

362

363

# Fall back to any available backend

364

try:

365

with audioread.audio_open(filepath) as f:

366

print(f"Opened with backend: {type(f).__name__}")

367

except audioread.NoBackendError:

368

print("No backend could open the file")

369

370

# Check what backends are available

371

backends = audioread.available_backends()

372

print("Available backends:")

373

for backend in backends:

374

print(f" - {backend.__name__}")

375

```