File I/O Operations
The io module reads and writes WAV and FLAC files. Reading and writing preserve the audio properties, and the sample type can be converted on load or save.
Reading Audio Files
- audio_samples.io.read(fp, as_type=None)
Read an audio file (WAV or FLAC) and return an
AudioSamples.- Parameters:
fp (str | Path | BinaryIO) – Path to the audio file, or a file object opened in binary mode with
read,seekandtell, read from its current position.as_type (SampleType | None) – Sample type to convert to, for example
SampleType.F32for floats in [-1, 1]. Defaults to the file’s native sample type (16-bit files give rawint16values).
- Returns:
The decoded audio.
- Return type:
- Raises:
FileNotFoundError – If
fpdoes not exist (AudioFileNotFoundError).TypeError – If the file cannot be decoded (
AudioDecodeError), orfpis neither a path nor a file object.ValueError – If a file object holds anything other than WAV or FLAC.
- audio_samples.io.read_with_info(fp, as_type=None)
Writing Audio Files
- audio_samples.io.save(fp, samples, as_type=None, flac_md5=True)
Save audio to a file, with the format chosen from the extension.
WAV keeps every sample type, float64 included. FLAC stores 16-bit and 24-bit integers only, so any other sample type raises
ValueErrorunlessas_typeasks forSampleType.I16orSampleType.I24.- Parameters:
fp (str | Path) – Output path.
samples (AudioSamples) – The audio to write.
as_type (SampleType, optional) – Convert to this sample type as the file is written, without a copy of the signal. Defaults to the audio’s native type.
flac_md5 (bool) – Store the MD5 signature of the audio in a FLAC file, so that decoders can verify it.
Falseleaves it out, which encodes faster. Defaults toTrue.
- Raises:
ValueError – If the format is unsupported, the sample type cannot be stored in FLAC, or
flac_md5is false and the file is not FLAC.OSError – If the file cannot be written.
- audio_samples.io.write_with_options(fp, samples, options=None, as_type=None, flac_md5=True)
Write audio samples to a file with explicit write options.
Like
save()but lets you control the write-buffer size viaWriteOptions. The format is chosen from the file extension (.wav/.flac/.aiff).- Parameters:
fp (str | Path) – Output path.
samples (AudioSamples) – The audio to write.
options (WriteOptions, optional) – Write options. Defaults to a 256-byte buffer, which holds the header.
as_type (SampleType, optional) – Convert to this sample type as the file is written, without a copy of the signal. Defaults to the audio’s native type.
flac_md5 (bool) – Store the MD5 signature of the audio in a FLAC file, so that decoders can verify it.
Falseleaves it out, which encodes faster. Defaults toTrue.
- Raises:
ValueError – If the format is unsupported, the file is FLAC and the sample type to write is not I16 or I24 (FLAC stores integers of those widths only), or
flac_md5is false and the file is not FLAC.OSError – If the file cannot be written.
- audio_samples.io.write_with_metadata(fp, samples, metadata)
Write a WAV file with trailing metadata chunks (LIST/INFO tags, cue points).
Like
save(), but also serialises the givenWavMetadataafter the audio data, persisting tags/markers that a plain read→write round-trip would drop. WAV only.- Parameters:
fp (str | Path) – Output
.wavpath.samples (AudioSamples) – The audio to write.
metadata (WavMetadata) – Metadata (INFO tags / cue points) to serialise.
- Raises:
OSError – If the file cannot be written.
Resampling on Read
- audio_samples.io.read_and_resample(fp, target_sr, quality=None, as_type=None)
Read an audio file and resample it to a target sample rate in one call.
Reads the entire file (auto-detecting WAV/FLAC), then resamples to
target_sr. The resampler is the same asAudioSamples.resample: delay-free, exactlyceil(n * target_sr / file_sr)samples per channel.- Parameters:
fp (str | Path) – Path to the audio file.
target_sr (int) – Target sample rate in Hz; must be greater than zero.
quality (ResamplingQuality, optional) – Resampling quality/speed trade-off. Defaults to
ResamplingQuality.highfor best fidelity.as_type (SampleType, optional) – Sample type for the returned audio. Defaults to the file’s sample type, as
read()does; the resampler works on every sample type.
- Returns:
The resampled audio.
- Return type:
- Raises:
ValueError – If
target_sris zero.TypeError – If the file cannot be read or the format is unsupported.
RuntimeError – If resampling fails.
- audio_samples.io.peek_native_type(fp)
Peek at the native sample type of an audio file with minimal I/O.
Reads only the header (no full decode), making it much cheaper than
info()when only the sample type is needed.- Parameters:
fp (str | Path) – Path to the audio file.
- Returns:
The native sample type as a string (e.g.
"i16","f32").- Return type:
- Raises:
ValueError – If the format is unsupported or the type cannot be determined.
OSError – If the file cannot be opened.
Streaming I/O
- class audio_samples.io.StreamedAudioReader(fp)
Bases:
objectA streaming audio file reader.
Opens a WAV or FLAC file and decodes frames on demand instead of loading the whole file into memory. Use it as a context manager and pull frames with
read_frames(), or iterate withframes(),windows(), orsamples().- Parameters:
fp (str | Path | BinaryIO) – Path to the audio file, or a binary file object with
read,seekandtell. The format is detected from the contents.- Raises:
OSError – If the file cannot be opened.
ValueError – If the format is unsupported or the header is corrupt.
- close()
Close the reader and release the underlying file handle.
Further reads raise
RuntimeError. Idempotent.
- current_frame
Current frame position (0-indexed).
- frames(chunk_frames=4096, dtype=None)
Return an iterator yielding fixed-size chunks of
chunk_framesframes.Each iteration calls
read_frames(); the final chunk may be shorter.- Parameters:
chunk_frames (int) – Frames per chunk; must be greater than zero. Defaults to 4096.
dtype (SampleType, optional) – Target sample type. Defaults to the file’s own sample type.
- Returns:
An iterator of
AudioSampleschunks.- Return type:
- num_channels
Number of audio channels.
- read_frames(frame_count, dtype=None)
Read up to
frame_countframes and return them as anAudioSamples.Frames are decoded and converted to the requested
dtypeon the fly. ReturnsNoneonce the end of the stream is reached (no frames left to read).- Parameters:
frame_count (int) – Maximum number of frames to read; must be greater than zero.
dtype (SampleType, optional) – Target sample type for the returned array. Defaults to the file’s own sample type.
- Returns:
The decoded chunk (mono shape
(frames,)or multi-channel shape(channels, frames)), orNoneat end of stream.- Return type:
AudioSamples | None
- Raises:
ValueError – If
frame_countis zero.RuntimeError – If the reader is closed.
OSError – If reading fails or the data is corrupt.
- remaining_frames
Number of frames remaining from the current position.
- reset()
Reset the stream to the beginning of the audio data.
- Raises:
OSError – If the underlying seek fails.
RuntimeError – If the reader is closed.
- sample_rate
Sample rate in Hz.
- samples(dtype=None)
Return an iterator yielding single frames (one frame per step).
Each item is an
AudioSamplesof one frame. This is convenient but slower thanframes(); prefer larger chunks for throughput.- Parameters:
dtype (SampleType, optional) – Target sample type. Defaults to the file’s own sample type.
- Returns:
An iterator of single-frame
AudioSamples.- Return type:
- seek_to_frame(frame)
Seek so the next read returns frame
frame.- Parameters:
frame (int) – Target frame index (0-indexed).
- Raises:
OSError – If the frame is beyond the end of the stream or the seek fails.
RuntimeError – If the reader is closed.
- total_frames
Total number of frames in the stream.
- windows(window, hop, dtype=None)
Return an iterator yielding overlapping windows.
Each window contains
windowframes; the read position advances byhopframes between windows (sohop < windowproduces overlap). Windows shorter thanwindowat the end of the stream are still yielded.- Parameters:
window (int) – Frames per window; must be greater than zero.
hop (int) – Frames to advance between windows; must be greater than zero.
dtype (SampleType, optional) – Target sample type. Defaults to the file’s own sample type.
- Returns:
An iterator of
AudioSampleswindows.- Return type:
- Raises:
ValueError – If
windoworhopis zero.
- class audio_samples.io.StreamedAudioWriter(fp, channels, sample_rate, dtype=None)
Bases:
objectA streaming audio file writer.
Encodes
AudioSampleschunks incrementally to a WAV or FLAC file (chosen from the extension) without buffering the whole signal. The output sample type is fixed at creation fromdtype. Alwaysfinalize()(or use thewithblock) so format headers are patched with the final sizes.- Parameters:
fp (str | Path) – Output path;
.wavor.flacselects the format.channels (int) – Number of channels; must be greater than zero.
sample_rate (int) – Sample rate in Hz; must be greater than zero.
dtype (SampleType, optional) – Output sample type. Defaults to
f32. FLAC supports only integer types (i16/i24/i32).
- Raises:
OSError – If the file cannot be created.
ValueError – If parameters are invalid or the type/format combination is unsupported.
- close()
Finalize (if not already) and release the file handle. Idempotent.
- Raises:
OSError – If finalization fails.
- static create_flac(fp, channels, sample_rate, compression=None, dtype=None)
Create a streaming FLAC writer with an explicit compression level.
- Parameters:
fp (str | Path) – Output
.flacpath.channels (int) – Number of channels; must be greater than zero.
sample_rate (int) – Sample rate in Hz; must be greater than zero.
compression (CompressionLevel, optional) – FLAC compression level (0-8). Defaults to the codec default (5).
dtype (SampleType, optional) – Integer output type (
i16/i24/i32). Defaults toi16.
- Returns:
A FLAC streaming writer.
- Return type:
- Raises:
OSError – If the file cannot be created.
ValueError – If the type is not a FLAC-supported integer type.
- finalize()
Finalize the stream, patching format headers with final sizes.
Must be called exactly once when writing is done (idempotent). After finalizing, further
write_frames()calls fail.- Raises:
RuntimeError – If the writer is closed.
OSError – If the underlying seek/flush fails.
- flush()
Flush buffered data to the underlying file without finalizing.
- Raises:
RuntimeError – If the writer is closed.
OSError – If the flush fails.
- frames_written
Number of frames written so far.
- is_finalized
Whether the stream has been finalized.
- num_channels
Number of channels the writer was configured with.
- sample_rate
Sample rate the writer was configured with, in Hz.
- write_frames(samples)
Write a chunk of audio frames to the stream.
Samples are converted from the array’s dtype to the writer’s configured output type. The channel count must match the writer’s configuration.
- Parameters:
samples (AudioSamples) – Frames to write.
- Returns:
The number of frames written.
- Return type:
- Raises:
RuntimeError – If the writer is closed or already finalized.
ValueError – If the channel count does not match.
OSError – If the underlying write fails.
- class audio_samples.io.WavSink(fp, channels, sample_rate, dtype=None, total_frames=None)
Bases:
objectA non-seekable streaming WAV writer (“sink”).
Writes a WAV stream to a file opened in append/write mode where seeking back to patch the header is undesirable. Because the header cannot be back-patched, the final frame count is either declared up front (
total_frames) or left open-ended (streaming-size convention).- Parameters:
fp (str | Path) – Output
.wavpath.channels (int) – Number of channels; must be greater than zero.
sample_rate (int) – Sample rate in Hz; must be greater than zero.
dtype (SampleType, optional) – Output sample type. Defaults to
i16.total_frames (int, optional) – Final frame count if known (produces a standard file and verifies the count on
finalize());Nonefor an open-ended stream.
- Raises:
OSError – If the file cannot be created.
ValueError – If parameters are invalid.
- close()
Finalize (if needed) and release the file handle. Idempotent.
- finalize()
Finalize the sink (idempotent). For a declared-length sink this verifies the count.
- flush()
Flush buffered data to the underlying file.
- frames_written
Number of frames written so far.
- write_frames(samples)
Write a chunk of audio frames to the sink.
- Parameters:
samples (AudioSamples) – Frames to write; channel count must match.
- Returns:
The number of frames written.
- Return type:
- Raises:
RuntimeError – If the sink is closed or finalized.
ValueError – If the channel count mismatches or the declared length is exceeded.
OSError – If the write fails.
- class audio_samples.io.StreamedFrameIterator
Bases:
objectIterator over chunks / windows / single frames of a
StreamedAudioReader.Created by
StreamedAudioReader.frames(),StreamedAudioReader.windows(), andStreamedAudioReader.samples(). YieldsAudioSamples; forhop != windowthe iterator seeks the underlying reader between steps.
Options and Metadata
- class audio_samples.io.WriteOptions(write_buf_capacity=None)
Bases:
objectOptions controlling how audio data is written.
- Parameters:
write_buf_capacity (int) – Size of the internal write buffer in bytes. The default of 256 holds only the file’s header: samples go straight to the file where their memory is already its layout, and otherwise in tiles of 64 KiB. A larger buffer copies them first, and helps only when each write call to the destination is expensive.
- write_buf_capacity
Size of the internal write buffer in bytes.
- class audio_samples.io.CompressionLevel(level=None)
Bases:
objectFLAC compression level (0-8): higher means smaller files but slower encoding.
- Parameters:
level (int) – Compression level, clamped to the range 0-8. Defaults to 5.
- static best()
Best compression (level 8).
- static fastest()
Fastest compression (level 0).
- level
The numeric compression level (0-8).
- class audio_samples.io.WavMetadata(info=None)
Bases:
objectRound-trippable WAV metadata: INFO tags plus cue points.
Pass to
write_with_metadata()to persist tags that a plain read→write would drop.- cue_points
The cue points (markers).
- info
The INFO tags, or
Noneif unset.
- is_empty
True if there are no tags and no cue points.
- class audio_samples.io.InfoMetadata
Bases:
objectLIST/INFO metadata tags for a WAV file (title, artist, etc.).
All fields are optional strings. Construct one and attach it to a
WavMetadatato persist tags withwrite_with_metadata().- album
Album name.
- artist
Performing artist.
- comment
Free-form comment.
- copyright
Copyright notice.
- date
Creation/release date.
- engineer
Engineer name.
- genre
Genre.
- keywords
Keywords.
- software
Authoring software.
- source
Source of the material.
- subject
Subject/description.
- title
Track title.
- class audio_samples.io.CuePoint
Bases:
objectA WAV cue point (marker).
- id
Cue point identifier.
- position
Play-order position.
- sample_offset
Sample offset within the data chunk.
- class audio_samples.io.VorbisComment
Bases:
objectA FLAC Vorbis comment block: a vendor string plus key→values tags.
Construct one, populate it with
set()/add(), and serialise withto_bytes()(or parse withfrom_bytes()). The comment block of a decoded FLAC file cannot be read back through this class; it constructs and (de)serialises comment blocks.- add(key, value)
Append
valueto the values forkey.
- static from_bytes(data)
Parse a Vorbis comment block from its raw bytes.
- Parameters:
data (bytes) – The raw Vorbis comment block.
- Returns:
The parsed comment.
- Return type:
- Raises:
ValueError – If the bytes are malformed.
- get(key)
Get the first value for
key, orNone.
- get_all(key)
Get all values for
key(empty list if absent).
- set(key, value)
Set
keyto a singlevalue, replacing any existing values.
- to_bytes()
Serialise to a raw Vorbis comment block.
- vendor
The vendor string.
- class audio_samples.io.StreamInfo
Bases:
objectFLAC STREAMINFO metadata block (read-only).
- bits_per_sample
Bits per sample.
- channels
Number of channels.
- has_md5
Whether the MD5 signature of the decoded audio is present.
- max_block_size
Maximum block size (samples).
- min_block_size
Minimum block size (samples).
- sample_rate
Sample rate in Hz.
- total_samples
Total inter-channel samples (frames).
- audio_samples.io.read_flac_stream_info(fp)
Read the STREAMINFO metadata block from a FLAC file.
- Parameters:
fp (str | Path) – Path to the FLAC file.
- Returns:
The FLAC STREAMINFO block.
- Return type:
- Raises:
OSError – If the file cannot be opened.
ValueError – If the file is not a FLAC file.
- audio_samples.io.read_wav_cue_points(fp)
Read the cue points (markers) from a WAV file.
- Parameters:
fp (str | Path) – Path to the WAV file.
- Returns:
The cue points (empty if none).
- Return type:
- Raises:
OSError – If the file cannot be opened.
ValueError – If the file is not a WAV file or the chunk is malformed.
- audio_samples.io.read_wav_info_tags(fp)
Read the LIST/INFO tags from a WAV file.
- Parameters:
fp (str | Path) – Path to the WAV file.
- Returns:
The INFO tags, or
Noneif the file has no LIST/INFO chunk.- Return type:
InfoMetadata | None
- Raises:
OSError – If the file cannot be opened.
ValueError – If the file is not a WAV file or the chunk is malformed.
File Information
- audio_samples.io.info(fp)
- class audio_samples.io.AudioInfo
Bases:
objectAudio file information structure
- bits_per_sample
Bits per sample
- channels
Number of audio channels
- duration
Duration in seconds
- num_samples
Total number of samples per channel
- sample_rate
Sample rate in Hz
- sample_type
Sample type as a string (e.g., “i16”, “f32”)
Examples
Basic File Operations
Read and write audio files with automatic format detection:
import audio_samples as aus
# Read audio file (format detected from extension)
audio = aus.io.read("input.wav")
# Audio properties are preserved automatically
print(f"Loaded: {audio.num_channels()} channel(s), {audio.sample_rate()} Hz")
print(f"Duration: {audio.duration_seconds():.2f} seconds")
# Process the audio
audio.scale(0.5) # Reduce volume by 50%
audio.fade_in(0.1, 'exponential') # 100ms fade-in
# Save with preserved format
aus.io.save("output.wav", audio)
Reading with Type Conversion
Control the data type during loading:
import numpy as np
# Read as specific type
audio_f32 = aus.io.read("audio.wav", as_type=np.float32)
audio_i16 = aus.io.read("audio.wav", as_type=np.int16)
# Check the resulting types
print(f"f32 audio dtype: {audio_f32.dtype}")
print(f"i16 audio dtype: {audio_i16.dtype}")
File Information Inspection
Get detailed information about audio files before loading:
# Read with metadata
audio, info = aus.io.read_with_info("large_file.wav")
print(f"File info:")
print(f" Sample rate: {info.sample_rate} Hz")
print(f" Channels: {info.channels}")
print(f" Bits per sample: {info.bits_per_sample}")
print(f" Duration: {info.duration:.2f} seconds")
print(f" Total samples per channel: {info.num_samples}")
print(f" Sample type: {info.sample_type}")
Format Conversion During Save
Convert audio format when saving via the as_type argument:
# Load audio (might be any format)
audio = aus.io.read("input.wav")
# Save as different formats
aus.io.save("output_16bit.wav", audio, as_type=np.int16)
aus.io.save("output_32bit.wav", audio, as_type=np.int32)
aus.io.save("output_float.wav", audio, as_type=np.float32)
Batch Processing
Process multiple files efficiently:
import pathlib
input_dir = pathlib.Path("input_files")
output_dir = pathlib.Path("processed_files")
output_dir.mkdir(exist_ok=True)
for wav_file in input_dir.glob("*.wav"):
# Read audio
audio = aus.io.read(str(wav_file))
# Apply consistent processing
audio.normalize(-1.0, 1.0, 'peak')
audio.remove_dc_offset()
# Save to output directory
output_path = output_dir / wav_file.name
aus.io.save(str(output_path), audio)
print(f"Processed {wav_file.name}")
Performance Considerations
To measure read speed:
import time
# Time file operations
start_time = time.time()
large_audio = aus.io.read("large_file.wav")
read_time = time.time() - start_time
print(f"Read {large_audio.duration_seconds():.1f}s of audio in {read_time:.4f}s")
print(f"Real-time factor: {large_audio.duration_seconds() / read_time:.1f}x")
# Time a save the same way
start_time = time.time()
aus.io.save("output_large.wav", large_audio)
write_time = time.time() - start_time
print(f"Wrote audio in {write_time:.4f}s")
print(f"Real-time factor: {large_audio.duration_seconds() / write_time:.1f}x")