Audio File Operations¶
The audio file module provides functionality for reading and writing audio files in various formats.
Object-Oriented API¶
AudioFile Class¶
The AudioFile class provides high-level audio file operations with automatic resource management.
import coremusic as cm
# Context manager usage (recommended)
with cm.AudioFile("audio.wav") as audio:
print(f"Duration: {audio.duration:.2f}s")
data, count = audio.read_packets(0, 1000)
# Explicit management
audio = cm.AudioFile("audio.wav")
audio.open()
try:
data = audio.read_packets(0, 1000)
finally:
audio.close()
Class Reference¶
coremusic.audio.AudioFile
¶
Bases: CoreAudioObject
High-level audio file operations with automatic resource management
Source code in src/coremusic/audio/core.py
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 | |
_path = str(path)
instance-attribute
¶
_format = None
instance-attribute
¶
_is_open = False
instance-attribute
¶
_writable = writable
instance-attribute
¶
format
property
¶
Get the audio format of the file
metadata
property
¶
Read the info dictionary metadata from the audio file.
Returns a dict with string keys and string/number/bytes values, or None if the file format does not support metadata.
duration
property
¶
Duration in seconds
__init__(path, *, writable=False)
¶
open()
¶
Open the audio file
Source code in src/coremusic/audio/core.py
close()
¶
Close the audio file
Source code in src/coremusic/audio/core.py
__enter__()
¶
__exit__(exc_type, exc_val, exc_tb)
¶
read_packets(start_packet, packet_count)
¶
Read audio packets from the file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_packet
|
int
|
Starting packet index (must be non-negative) |
required |
packet_count
|
int
|
Number of packets to read (must be positive) |
required |
Returns:
| Type | Description |
|---|---|
tuple[bytes, int]
|
Tuple of (audio_data_bytes, packets_read) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If start_packet < 0 or packet_count <= 0 |
AudioFileError
|
If reading fails |
Example::
from coremusic.audio import AudioFile
# Read audio data in chunks
with AudioFile("audio.wav") as audio:
chunk_size = 4096
offset = 0
while True:
data, packets_read = audio.read_packets(offset, chunk_size)
if packets_read == 0:
break
# Process data...
offset += packets_read
Source code in src/coremusic/audio/core.py
read_as_numpy(start_packet=0, packet_count=None)
¶
Read audio data from the file as a NumPy array.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_packet
|
int
|
Starting packet index (default: 0) |
0
|
packet_count
|
int | None
|
Number of packets to read (default: all remaining packets) |
None
|
Returns:
| Type | Description |
|---|---|
'NDArray[Any]'
|
NumPy array with shape (frames, channels) for multi-channel audio, |
'NDArray[Any]'
|
or (frames,) for mono audio. The dtype is determined by the audio format. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If NumPy is not available |
AudioFileError
|
If reading fails |
Example:
with AudioFile("audio.wav") as audio:
data = audio.read_as_numpy()
print(f"Shape: {data.shape}, dtype: {data.dtype}")
# output: Shape: (44100, 2), dtype: int16
Source code in src/coremusic/audio/core.py
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | |
get_property(property_id)
¶
Get a property from the audio file
Source code in src/coremusic/audio/core.py
set_property(property_id, data)
¶
Set a property on the audio file.
The file must have been opened with writable=True.
Source code in src/coremusic/audio/core.py
set_metadata(tags)
¶
Write metadata tags to the audio file.
The file must have been opened with writable=True. Keys should be strings. Values can be str, int, or float.
Common keys: 'title', 'artist', 'album', 'genre', 'year', 'track number', 'comments', 'approximate duration in seconds'.
Source code in src/coremusic/audio/core.py
__repr__()
¶
dispose()
¶
Dispose of the audio file
Source code in src/coremusic/audio/core.py
AudioFormat Class¶
The AudioFormat class represents audio stream format information.
import coremusic as cm
# Access format from audio file
with cm.AudioFile("audio.wav") as audio:
fmt = audio.format
print(f"Sample rate: {fmt.sample_rate}Hz")
print(f"Channels: {fmt.channels_per_frame}")
print(f"Bit depth: {fmt.bits_per_channel}")
# Create custom format
format = cm.AudioFormat(
sample_rate=44100.0,
format_id='lpcm',
channels_per_frame=2,
bits_per_channel=16
)
Class Reference¶
coremusic.audio.AudioFormat
¶
Pythonic representation of AudioStreamBasicDescription
Source code in src/coremusic/audio/core.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 | |
sample_rate = sample_rate
instance-attribute
¶
format_id = format_id
instance-attribute
¶
format_flags = format_flags
instance-attribute
¶
bytes_per_packet = bytes_per_packet
instance-attribute
¶
frames_per_packet = frames_per_packet
instance-attribute
¶
bytes_per_frame = bytes_per_frame
instance-attribute
¶
channels_per_frame = channels_per_frame
instance-attribute
¶
bits_per_channel = bits_per_channel
instance-attribute
¶
is_pcm
property
¶
Check if this is a PCM format
is_stereo
property
¶
Check if this is stereo (2 channels)
is_mono
property
¶
Check if this is mono (1 channel)
__init__(sample_rate, format_id, format_flags=0, bytes_per_packet=0, frames_per_packet=0, bytes_per_frame=0, channels_per_frame=2, bits_per_channel=16)
¶
Source code in src/coremusic/audio/core.py
from_asbd_bytes(data)
classmethod
¶
Parse an AudioStreamBasicDescription (40 bytes) into an AudioFormat.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
bytes
|
Raw ASBD bytes (at least 40 bytes) |
required |
Returns:
| Type | Description |
|---|---|
'AudioFormat'
|
AudioFormat with parsed fields |
Raises:
| Type | Description |
|---|---|
ValueError
|
If data is too short |
Source code in src/coremusic/audio/core.py
pcm(sample_rate=44100.0, channels=2, bits=16, is_float=False)
classmethod
¶
Create a PCM AudioFormat with correctly computed derived fields.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sample_rate
|
float
|
Sample rate in Hz (default: 44100.0) |
44100.0
|
channels
|
int
|
Number of channels (default: 2) |
2
|
bits
|
int
|
Bits per sample (default: 16) |
16
|
is_float
|
bool
|
If True, create float format; otherwise signed integer |
False
|
Returns:
| Type | Description |
|---|---|
'AudioFormat'
|
AudioFormat with all ASBD fields correctly computed |
Source code in src/coremusic/audio/core.py
to_dict()
¶
Convert to dictionary format for functional API
Source code in src/coremusic/audio/core.py
to_numpy_dtype()
¶
Convert audio format to NumPy dtype for audio data arrays.
Returns:
| Type | Description |
|---|---|
'np.dtype[Any]'
|
NumPy dtype object suitable for audio data representation |
Raises:
| Type | Description |
|---|---|
ImportError
|
If NumPy is not available |
ValueError
|
If format cannot be converted to NumPy dtype |
Source code in src/coremusic/audio/core.py
Functional API¶
The functional API provides direct access to CoreAudio file operations through
the coremusic.capi module.
Note
The object-oriented AudioFile API is recommended for most use cases.
Use the functional API only when you need fine-grained control.
Opening and Closing Files¶
Example:
import coremusic.capi as capi
# Open audio file
file_id = capi.audio_file_open_url("audio.wav")
try:
# Use file...
pass
finally:
capi.audio_file_close(file_id)
Reading Audio Data¶
Example:
import coremusic.capi as capi
file_id = capi.audio_file_open_url("audio.wav")
try:
# Read 1000 packets starting from packet 0
data, packets_read = capi.audio_file_read_packets(file_id, 0, 1000)
print(f"Read {packets_read} packets, {len(data)} bytes")
finally:
capi.audio_file_close(file_id)
File Properties¶
Example:
import coremusic.capi as capi
file_id = capi.audio_file_open_url("audio.wav")
try:
# Get audio format
format_data = capi.audio_file_get_property(
file_id,
capi.get_audio_file_property_data_format()
)
print(f"Format: {format_data}")
finally:
capi.audio_file_close(file_id)
Supported Formats¶
coremusic supports all audio formats supported by CoreAudio, including:
Common Formats¶
- WAV (Waveform Audio File Format)
- AIFF (Audio Interchange File Format)
- MP3 (MPEG-1 Audio Layer 3)
- AAC (Advanced Audio Coding)
- ALAC (Apple Lossless Audio Codec)
- FLAC (Free Lossless Audio Codec)
Format IDs¶
Common format IDs (FourCC codes):
'lpcm'- Linear PCM (uncompressed)'aac '- AAC'.mp3'- MP3'alac'- Apple Lossless'flac'- FLAC
Format Flags¶
For Linear PCM, common format flags include:
- Float vs Integer
- Big Endian vs Little Endian
- Packed vs Aligned
- Signed vs Unsigned
Use the provided constant functions to get appropriate flags:
import coremusic.capi as capi
# Get standard format flags
flags = capi.get_audio_format_flag_is_float() | \
capi.get_audio_format_flag_is_packed()
Examples¶
Read Entire Audio File¶
import coremusic as cm
def read_audio_file(filepath):
"""Read entire audio file into memory."""
with cm.AudioFile(filepath) as audio:
# Get total frame count
total_frames = audio.frame_count
# Read all data
data, count = audio.read_packets(0, total_frames)
return {
'data': data,
'sample_rate': audio.format.sample_rate,
'channels': audio.format.channels_per_frame,
'format': audio.format.format_id
}
# Use the function
audio_data = read_audio_file("audio.wav")
print(f"Loaded {len(audio_data['data'])} bytes")
Process Audio in Chunks¶
import coremusic as cm
def process_audio_chunks(filepath, chunk_size=1024):
"""Process audio file in chunks."""
with cm.AudioFile(filepath) as audio:
total_frames = audio.frame_count
current_frame = 0
while current_frame < total_frames:
# Calculate chunk size
frames_to_read = min(chunk_size, total_frames - current_frame)
# Read chunk
data, count = audio.read_packets(current_frame, frames_to_read)
# Process chunk
process_audio_data(data)
current_frame += count
def process_audio_data(data):
"""Process audio data chunk."""
# Your processing logic here
pass
Audio Format Conversion¶
import coremusic as cm
def convert_audio_format(input_path, output_path, target_format):
"""Convert audio file to different format."""
# Open input file
with cm.AudioFile(input_path) as input_audio:
# Create converter
converter = cm.AudioConverter(input_audio.format, target_format)
# Read and convert
data, count = input_audio.read_packets(0, input_audio.frame_count)
converted_data = converter.convert(data, count)
# Write to output file
# (implementation depends on output requirements)