### Install audioread Source: https://context7.com/beetbox/audioread/llms.txt Install audioread using pip. Ensure at least one backend, like FFmpeg, is available. ```bash pip install audioread ``` -------------------------------- ### Specify Backends for Audio Opening Source: https://github.com/beetbox/audioread/blob/main/README.rst Optionally specify which backends audioread.audio_open should try. Use available_backends() to get a list of usable backends on the current system. ```python import audioread # Example: Try only FFmpeg and GStreamer backends with audioread.audio_open(filename, backend='ffmpeg,gstreamer') as f: pass # Get available backends on the system print(audioread.available_backends()) ``` -------------------------------- ### GStreamer Backend for Audio Decoding Source: https://context7.com/beetbox/audioread/llms.txt Use the GStreamer backend for decoding various audio formats if GStreamer is installed. Handles potential decoding errors and missing streams. ```python from audioread.gstdec import ( GstAudioFile, UnknownTypeError, FileReadError, NoStreamError, MetadataMissingError, ) try: with GstAudioFile("podcast.ogg") as f: print(f"Channels : {f.channels}") print(f"Sample rate: {f.samplerate} Hz") print(f"Duration : {f.duration:.2f}s") block_count = 0 for buf in f: # Each buf is bytes of 16-bit LE signed PCM block_count += 1 print(f"Decoded {block_count} blocks") except UnknownTypeError as e: print(f"GStreamer cannot decode stream: {e.streaminfo}") except NoStreamError: print("File contained no decodable audio stream.") except FileReadError as e: print(f"GStreamer failed to read the file: {e}") except MetadataMissingError: print("GStreamer could not determine stream duration.") ``` -------------------------------- ### MAD Backend for MP3 Decoding Source: https://context7.com/beetbox/audioread/llms.txt Utilizes the libmad library via pymad for decoding MP1, MP2, and MP3 files. Outputs are always mono or stereo 16-bit signed PCM. Requires `pip install pymad` and the libmad system library. ```python from audioread.maddec import MadAudioFile, UnsupportedError try: with MadAudioFile("music.mp3") as f: print(f"Channels : {f.channels}") print(f"Sample rate: {f.samplerate} Hz") print(f"Duration : {f.duration:.2f}s") for block in f: # block is bytes of 16-bit signed PCM process_audio(block) except UnsupportedError: print("File is not readable by libmad (not an MPEG audio file).") ``` -------------------------------- ### Pre-query available backends Source: https://context7.com/beetbox/audioread/llms.txt For performance-sensitive applications, cache the result of `audioread.available_backends()` once at startup to avoid repeated backend detection in subsequent `audio_open` calls. ```python backends = audioread.available_backends() with audioread.audio_open(path, backend_cache=backends) as f: # process audio file pass ``` -------------------------------- ### Raw Audio File Backend Usage Source: https://context7.com/beetbox/audioread/llms.txt Demonstrates how to use the RawAudioFile backend for decoding uncompressed audio formats using only standard Python libraries. ```APIDOC ## `RawAudioFile(path)` ### Description Reads uncompressed WAV, AIFF, AIFF-C, and Au/SND files using only Python's built-in `wave`, `aifc`, and `sunau` modules — no external tools required. Automatically converts any bit depth (8, 16, 24, or 32-bit) to 16-bit output and handles endianness swapping for big-endian formats (AIFF, Au). Raises `UnsupportedError` if the file is not one of the supported formats. ### Parameters #### Path Parameters - **path** (string) - Required - The path to the audio file to decode. ### Request Example ```python from audioread.rawread import RawAudioFile, UnsupportedError, BitWidthError # Read a WAV file with the raw backend only try: with RawAudioFile("recording.wav") as f: print(f"Channels : {f.channels}") print(f"Sample rate: {f.samplerate} Hz") print(f"Duration : {f.duration:.3f}s") pcm_data = bytearray() for block in f: pcm_data.extend(block) print(f"Total PCM bytes read: {len(pcm_data)}") # PCM is always 16-bit little-endian signed integers expected = int(f.samplerate * f.duration) * f.channels * 2 print(f"Expected ~{expected} bytes") except UnsupportedError: print("Not a WAV/AIFF/Au file — use a different backend.") except BitWidthError: print("Unsupported bit depth (only 8/16/24/32-bit are supported).") ``` ### Response #### Success Response (decoded audio data) - Iterates over blocks of decoded PCM audio data. #### Error Responses - **`UnsupportedError`**: Raised if the file format is not supported by the raw backend. - **`BitWidthError`**: Raised if the audio file has an unsupported bit depth. ``` -------------------------------- ### Python WAV Conversion using audioread Source: https://context7.com/beetbox/audioread/llms.txt This Python script demonstrates the equivalent logic of `decode.py` for converting audio files to WAV format using `audioread.audio_open` and the `wave` module. It handles file paths and potential decoding errors. ```python import audioread, wave, contextlib, os def decode_to_wav(input_path): input_path = os.path.abspath(os.path.expanduser(input_path)) output_path = input_path + ".wav" try: with audioread.audio_open(input_path) as f: print(f"Input: {f.channels}ch @ {f.samplerate}Hz, {f.duration:.1f}s") print(f"Backend: {type(f).__module__.split('.')[1]}") with contextlib.closing(wave.open(output_path, "w")) as out: out.setnchannels(f.channels) out.setframerate(f.samplerate) out.setsampwidth(2) for buf in f: out.writeframes(buf) print(f"Wrote: {output_path}") except audioread.DecodeError: print("Decoding failed.") decode_to_wav("~/Music/track.flac") ``` -------------------------------- ### Open and read audio file Source: https://context7.com/beetbox/audioread/llms.txt Use the `audioread.audio_open` context manager to read audio data from any supported format. This pattern is suitable for general audio processing tasks. ```python import audioread with audioread.audio_open(path) as f: for buf in f: # process audio buffer 'buf' pass ``` -------------------------------- ### List and Use Specific Backends with audioread Source: https://context7.com/beetbox/audioread/llms.txt Retrieves a list of available audio decoding backends on the system and demonstrates how to restrict `audio_open` to specific backends. The backend list is cached and can be flushed. ```python import audioread from audioread.ffdec import FFmpegAudioFile from audioread.rawread import RawAudioFile # Inspect what's available backends = audioread.available_backends() print("Backends on this system:") for b in backends: print(f" {b.__module__}.{b.__name__}") # Example output: # audioread.rawread.RawAudioFile # audioread.ffdec.FFmpegAudioFile # Flush cache after installing a new tool at runtime backends = audioread.available_backends(flush_cache=True) # Restrict to only the standard-library backend (no external deps) with audioread.audio_open("audio.wav", backends=[RawAudioFile]) as f: print(f"Duration: {f.duration:.2f}s") # Restrict to only FFmpeg (skip slower backends) if FFmpegAudioFile in backends: with audioread.audio_open("audio.mp3", backends=[FFmpegAudioFile]) as f: for buf in f: pass else: print("FFmpeg not available; install ffmpeg or libav.") ``` -------------------------------- ### audioread.available_backends Source: https://context7.com/beetbox/audioread/llms.txt Returns a list of backend classes that are usable on the current system. The result is cached by default, but can be flushed to force re-detection. This is useful for inspecting available decoders or restricting `audio_open` to specific backends. ```APIDOC ## audioread.available_backends(flush_cache=False) ### Description Returns a list of backend classes that are usable on the current system. The result is cached after the first call; pass `flush_cache=True` to force re-detection. The list always starts with `RawAudioFile` (standard library) and may include `ExtAudioFile` (macOS only), `GstAudioFile` (GStreamer), `MadAudioFile` (pymad), and `FFmpegAudioFile` depending on what is installed. ### Parameters #### Query Parameters - **flush_cache** (boolean) - Optional - Defaults to `False`. If `True`, forces re-detection of available backends. ### Request Example ```python import audioread from audioread.ffdec import FFmpegAudioFile from audioread.rawread import RawAudioFile backends = audioread.available_backends() print("Backends on this system:") for b in backends: print(f" {b.__module__}.{b.__name__}") # Example: Restrict to only the standard-library backend with audioread.audio_open("audio.wav", backends=[RawAudioFile]) as f: print(f"Duration: {f.duration:.2f}s") # Example: Restrict to only FFmpeg if FFmpegAudioFile in backends: with audioread.audio_open("audio.mp3", backends=[FFmpegAudioFile]) as f: for buf in f: pass else: print("FFmpeg not available; install ffmpeg or libav.") ``` ``` -------------------------------- ### FFmpeg Backend Usage Source: https://context7.com/beetbox/audioread/llms.txt Shows how to use the FFmpeg backend directly for decoding audio files, including error handling for common FFmpeg issues. ```APIDOC ## `FFmpegAudioFile(path, block_size)` ### Description Decodes audio by spawning an `ffmpeg` (or `avconv`) subprocess and reading raw PCM from its stdout via a background thread. Accepts an optional `block_size` parameter controlling the read buffer size (default: `io.DEFAULT_BUFFER_SIZE`). Stream metadata (`samplerate`, `channels`, `duration`) is parsed from FFmpeg's stderr output. The process is killed and threads are joined on `close()`. ### Parameters #### Path Parameters - **path** (string) - Required - The path to the audio file to decode. - **block_size** (int) - Optional - The size of the read buffer (default: `io.DEFAULT_BUFFER_SIZE`). ### Request Example ```python from audioread.ffdec import FFmpegAudioFile, available, ReadTimeoutError import wave, contextlib # Check FFmpeg availability before use if not available(): raise RuntimeError("Install ffmpeg: https://ffmpeg.org/download.html") # Decode an MP3 to WAV using the FFmpeg backend directly input_path = "input.mp3" output_path = "output.wav" with FFmpegAudioFile(input_path, block_size=65536) as f: print(f"FFmpeg decoded: {f.channels}ch @ {f.samplerate}Hz, {f.duration:.1f}s") with contextlib.closing(wave.open(output_path, "w")) as wav: wav.setnchannels(f.channels) wav.setframerate(f.samplerate) wav.setsampwidth(2) # 16-bit output try: for buf in f: wav.writeframes(buf) except ReadTimeoutError: print("FFmpeg stopped responding; output may be incomplete.") print(f"Wrote: {output_path}") ``` ### Response #### Success Response (decoded audio data) - Iterates over blocks of decoded PCM audio data. #### Error Responses - **`ReadTimeoutError`**: Raised if FFmpeg stops responding during reading. - **`NotInstalledError`**: Raised if ffmpeg/avconv binary is not found in PATH. - **`UnsupportedError`**: Raised if FFmpeg cannot decode the file format. - **`CommunicationError`**: Raised if there's an issue parsing FFmpeg output. ``` -------------------------------- ### audioread.audio_open Source: https://context7.com/beetbox/audioread/llms.txt Opens an audio file using the best available backend on the current system. It returns an audio file object that provides access to stream metadata and raw PCM data. Error handling for missing files or unsupported formats is also demonstrated. ```APIDOC ## audioread.audio_open(path, backends=None) ### Description Opens an audio file using the best available backend on the current system, returning an audio file object whose type depends on the backend selected. The optional `backends` parameter accepts a list of backend classes to try; if omitted, all available backends are tried in order. Raises `NoBackendError` (a subclass of `DecodeError`) if no backend can open the file, or a standard `IOError` if the file does not exist. ### Parameters #### Path Parameters - **path** (string) - Required - The path to the audio file. - **backends** (list of backend classes) - Optional - A list of backend classes to try in order. ### Request Example ```python import audioread with audioread.audio_open("song.mp3") as f: print(f"Channels : {f.channels}") print(f"Sample rate: {f.samplerate} Hz") print(f"Duration : {f.duration:.2f}s") for buf in f: # Process raw PCM data pass ``` ### Error Handling ```python try: with audioread.audio_open("unknown_format.xyz") as f: for buf in f: pass except audioread.NoBackendError: print("No available backend could decode this file.") except IOError: print("File not found or unreadable.") ``` ### Targeting Specific Backends ```python import audioread backends = audioread.available_backends() with audioread.audio_open("audio.wav", backends=backends) as f: for buf in f: pass ``` ``` -------------------------------- ### Open Audio File and Read PCM Data with audioread Source: https://context7.com/beetbox/audioread/llms.txt Opens an audio file using the best available backend, inspects metadata (channels, samplerate, duration), and iterates over raw PCM data blocks. Handles potential decoding errors and file not found exceptions. ```python import audioread import struct # --- Basic usage: inspect metadata and read PCM blocks --- with audioread.audio_open("song.mp3") as f: print(f"Channels : {f.channels}") # e.g. 2 print(f"Sample rate: {f.samplerate} Hz") # e.g. 44100 print(f"Duration : {f.duration:.2f}s") # e.g. 213.40 total_bytes = 0 for buf in f: # buf is raw 16-bit little-endian signed PCM bytes assert isinstance(buf, (bytes, bytearray, memoryview)) total_bytes += len(buf) num_samples = total_bytes // 2 # 2 bytes per 16-bit sample print(f"Total samples per channel: {num_samples // f.channels}") # --- Error handling --- try: with audioread.audio_open("unknown_format.xyz") as f: for buf in f: pass except audioread.NoBackendError: print("No available backend could decode this file.") except IOError: print("File not found or unreadable.") # --- Targeting specific backends --- backends = audioread.available_backends() print("Available backends:", [b.__name__ for b in backends]) # e.g. [RawAudioFile, FFmpegAudioFile] with audioread.audio_open("audio.wav", backends=backends) as f: for buf in f: process(buf) ``` -------------------------------- ### Core Audio Backend for macOS Source: https://context7.com/beetbox/audioread/llms.txt This backend is macOS-specific and utilizes the Core Audio framework. It decodes any format supported by Core Audio and always outputs 16-bit signed little-endian PCM. ```python import sys if sys.platform != "darwin": raise RuntimeError("Core Audio backend is macOS-only.") from audioread.macca import ExtAudioFile, MacError with ExtAudioFile("track.m4a") as f: print(f"Channels : {f.channels}") print(f"Sample rate: {f.samplerate} Hz") print(f"Duration : {f.duration:.2f}s") print(f"Frames : {f.nframes}") total = 0 for buf in f: total += len(buf) print(f"PCM bytes read: {total}") # Verify: nframes * channels * 2 bytes/sample expected = f.nframes * f.channels * 2 print(f"Expected : {expected}") ``` -------------------------------- ### Command-line WAV Conversion with decode.py Source: https://context7.com/beetbox/audioread/llms.txt The `decode.py` script converts any supported audio format to WAV using the `audioread.audio_open` function. It prints backend information to stderr and creates a WAV file named `.wav`. ```bash # Convert an MP3 to WAV python decode.py song.mp3 # stderr: Input file: 2 channels at 44100 Hz; 213.4 seconds. # stderr: Backend: ffdec # Creates: song.mp3.wav ``` -------------------------------- ### Decode Audio with FFmpeg Backend Source: https://context7.com/beetbox/audioread/llms.txt Use FFmpegAudioFile for decoding audio files by spawning an ffmpeg/avconv subprocess. Ensure FFmpeg is available and handle potential ReadTimeoutError during processing. ```python from audioread.ffdec import FFmpegAudioFile, available, ReadTimeoutError import wave, contextlib # Check FFmpeg availability before use if not available(): raise RuntimeError("Install ffmpeg: https://ffmpeg.org/download.html") # Decode an MP3 to WAV using the FFmpeg backend directly input_path = "input.mp3" output_path = "output.wav" with FFmpegAudioFile(input_path, block_size=65536) as f: print(f"FFmpeg decoded: {f.channels}ch @ {f.samplerate}Hz, {f.duration:.1f}s") with contextlib.closing(wave.open(output_path, "w")) as wav: wav.setnchannels(f.channels) wav.setframerate(f.samplerate) wav.setsampwidth(2) # 16-bit output try: for buf in f: wav.writeframes(buf) except ReadTimeoutError: print("FFmpeg stopped responding; output may be incomplete.") print(f"Wrote: {output_path}") ``` -------------------------------- ### Open and Read Audio File with Audioread Source: https://github.com/beetbox/audioread/blob/main/README.rst Use audioread.audio_open to open an audio file and iterate over its decoded PCM data buffers. The file object provides access to channels, samplerate, and duration. Buffers contain raw 16-bit little-endian signed integer PCM data. ```python import audioread filename = "your_audio_file.mp3" with audioread.audio_open(filename) as f: print(f.channels, f.samplerate, f.duration) for buf in f: # Process the audio buffer (buf) pass ``` -------------------------------- ### Target specific backend Source: https://context7.com/beetbox/audioread/llms.txt Custom processing pipelines can directly target specific backend classes, such as `FFmpegAudioFile`, for more control. Fall back to `audio_open` for format-agnostic handling. ```python from audioread.ffdec import FFmpegAudioFile with FFmpegAudioFile(path) as f: # process audio file using FFmpeg backend pass ``` -------------------------------- ### GStreamer Backend Usage Source: https://context7.com/beetbox/audioread/llms.txt Details on using the GStreamer backend for decoding a wide range of audio formats via PyGObject. ```APIDOC ## `GstAudioFile(path)` ### Description Decodes audio using GStreamer 1.x via PyGObject, supporting any container/codec that GStreamer can handle (MP3, AAC, OGG, FLAC, etc.). Internally builds a GStreamer pipeline (`uridecodebin → audioconvert → appsink`) and feeds decoded buffers into a Python `queue.Queue`. The library manages a single shared daemon thread running a `GLib.MainLoop`; each file must be explicitly closed (or used as a context manager) to avoid hanging the process. ### Parameters #### Path Parameters - **path** (string) - Required - The path to the audio file to decode. ### Request Example ```python # Requires: pip install PyGObject # Example usage would follow, similar to other backends. ``` ### Response #### Success Response (decoded audio data) - Iterates over blocks of decoded PCM audio data. #### Error Responses - Specific error types for GStreamer backend issues would be detailed here if provided in the source. ``` -------------------------------- ### Read Audio with Standard Library Backend Source: https://context7.com/beetbox/audioread/llms.txt Utilize RawAudioFile for decoding uncompressed WAV, AIFF, and Au files using only Python's built-in modules. This backend automatically handles bit depth conversion and endianness, raising UnsupportedError or BitWidthError for unsupported formats or bit depths. ```python from audioread.rawread import RawAudioFile, UnsupportedError, BitWidthError # Read a WAV file with the raw backend only try: with RawAudioFile("recording.wav") as f: print(f"Channels : {f.channels}") print(f"Sample rate: {f.samplerate} Hz") print(f"Duration : {f.duration:.3f}s") pcm_data = bytearray() for block in f: pcm_data.extend(block) print(f"Total PCM bytes read: {len(pcm_data)}") # PCM is always 16-bit little-endian signed integers expected = int(f.samplerate * f.duration) * f.channels * 2 print(f"Expected ~{expected} bytes") except UnsupportedError: print("Not a WAV/AIFF/Au file — use a different backend.") except BitWidthError: print("Unsupported bit depth (only 8/16/24/32-bit are supported).") ``` -------------------------------- ### Handle audioread Decoding Errors Source: https://context7.com/beetbox/audioread/llms.txt Use this pattern to safely open audio files and handle potential decoding errors or file I/O issues. For FFmpeg-specific errors, target FFmpegAudioFile directly. ```python import audioread from audioread.ffdec import ( NotInstalledError, ReadTimeoutError, UnsupportedError, CommunicationError, ) from audioread.rawread import UnsupportedError as RawUnsupportedError def safe_get_duration(path): """Return duration in seconds or None on any failure.""" try: with audioread.audio_open(path) as f: return f.duration except audioread.NoBackendError: # Covers: no backends installed, file type unsupported by all backends return None except IOError: # File missing or permission denied return None # Fine-grained handling when targeting FFmpeg directly from audioread.ffdec import FFmpegAudioFile try: with FFmpegAudioFile("audio.mp3") as f: for buf in f: pass except NotInstalledError: print("ffmpeg / avconv binary not found in PATH.") except ReadTimeoutError as e: print(f"FFmpeg hung reading the file: {e}") except UnsupportedError: print("FFmpeg cannot decode this file format.") except CommunicationError as e: print(f"Could not parse FFmpeg output: {e}") ``` -------------------------------- ### Safe Duration Retrieval Source: https://context7.com/beetbox/audioread/llms.txt Demonstrates how to safely retrieve the duration of an audio file, handling potential decoding and IO errors. ```APIDOC ## `safe_get_duration(path)` ### Description Return duration in seconds or None on any failure. ### Parameters #### Path Parameters - **path** (string) - Required - The path to the audio file. ### Request Example ```python import audioread def safe_get_duration(path): """Return duration in seconds or None on any failure.""" try: with audioread.audio_open(path) as f: return f.duration except audioread.NoBackendError: # Covers: no backends installed, file type unsupported by all backends return None except IOError: # File missing or permission denied return None ``` ### Response #### Success Response (float) - Returns the duration of the audio file in seconds. #### Failure Response (None) - Returns None if any error occurs during decoding or file access. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.