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.
from coremusic.audio import AudioFile
# Context manager usage (recommended)
with AudioFile("audio.wav") as audio:
print(f"Duration: {audio.duration:.2f}s")
data, count = audio.read_packets(0, 1000)
# Explicit management
audio = 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
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 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 | |
_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.
path
property
¶
Path the file was opened from
packet_count
property
¶
Number of audio packets in the file.
For uncompressed PCM one packet is one frame, so this is also the frame
count. It is the upper bound for :meth:read_packets.
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
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 | |
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.
from coremusic.audio import AudioFile, AudioFormat
# Access format from audio file
with 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 = 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
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 235 236 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 | |
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_compressed
property
¶
Check if this is a compressed (non-PCM) format coremusic can encode.
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, big_endian=False)
classmethod
¶
Create a packed 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
|
big_endian
|
bool
|
If True, mark the samples as big-endian. macOS is little-endian natively, so set this only for containers that require it, such as AIFF. |
False
|
Returns:
| Type | Description |
|---|---|
AudioFormat
|
AudioFormat with all ASBD fields correctly computed |
Source code in src/coremusic/audio/core.py
aac(sample_rate=44100.0, channels=2)
classmethod
¶
Create an AAC (lossy) compressed format description.
The returned description is suitable as the file format when creating an ExtAudioFile for encoding; the PCM feed is supplied separately as the client format. CoreAudio fills in the encoder-specific fields, so the packet/frame/bit fields are left at their canonical AAC values.
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
|
Source code in src/coremusic/audio/core.py
alac(sample_rate=44100.0, channels=2)
classmethod
¶
Create an Apple Lossless (ALAC) compressed format description.
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
|
Source code in src/coremusic/audio/core.py
flac(sample_rate=44100.0, channels=2)
classmethod
¶
Create a FLAC (lossless) compressed format description.
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
|
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 |
|---|---|
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:
from coremusic import 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:
from coremusic import 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:
from coremusic import 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:
from coremusic.constants import LinearPCMFormatFlag
# Standard packed float PCM
flags = LinearPCMFormatFlag.IS_FLOAT | LinearPCMFormatFlag.IS_PACKED
# Standard packed signed-integer PCM
int_flags = LinearPCMFormatFlag.IS_SIGNED_INTEGER | LinearPCMFormatFlag.IS_PACKED
# AudioFormat.pcm() builds these for you
from coremusic.audio import AudioFormat
float_format = AudioFormat.pcm(44100.0, channels=2, bits=32, is_float=True)
assert float_format.format_flags == flags
Examples¶
Read Entire Audio File¶
from coremusic.audio import AudioFile
def read_audio_file(filepath):
"""Read entire audio file into memory."""
with AudioFile(filepath) as audio:
# Get total frame count
total_frames = audio.packet_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¶
from coremusic.audio import AudioFile
def process_audio_chunks(filepath, chunk_size=1024):
"""Process audio file in chunks."""
with AudioFile(filepath) as audio:
total_frames = audio.packet_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
process_audio_chunks("audio.wav")
Audio Format Conversion¶
from coremusic import capi
from coremusic.audio import AudioConverter, AudioFile, AudioFormat, ExtendedAudioFile
def convert_audio_format(input_path, output_path, target_format):
"""Convert audio file to different format."""
# Open input file
with AudioFile(input_path) as input_audio:
# Create converter
converter = AudioConverter(input_audio.format, target_format)
# Read and convert. convert() handles depth and channel changes; a
# change of sample rate needs convert_with_callback().
data, count = input_audio.read_packets(0, input_audio.packet_count)
converted = converter.convert(data)
# Write to output file
with ExtendedAudioFile.create(
output_path, capi.fourchar_to_int('WAVE'), target_format
) as output_audio:
output_audio.write(len(converted) // target_format.bytes_per_frame, converted)
convert_audio_format(
"audio.wav",
"converted.wav",
AudioFormat.pcm(44100.0, channels=2, bits=32, is_float=True),
)