audioread

repository·main·Indexed 19 days ago

https://github.com/beetbox/audioread

A Python library for multi-library, cross-platform audio decoding. It provides a transparent interface to decode various audio formats using available backends such as FFmpeg, GStreamer, Core Audio, MAD, and standard library modules. The library yields raw 16-bit little-endian signed integer PCM data and provides metadata including channels, samplerate, and duration.

Tokens
1.6K
Snippets
6
Records
11
Agent score
67%

What's inside audioread

  1. Troubleshoot NoBackendError

    main

    If you encounter a NoBackendError, it means a required external dependency is missing or misconfigured.

    For example, if the FFmpeg backend is failing, verify your installation by running ffmpeg -version in your terminal. If it is not found, install it using your OS package manager (e.g., apt or yum) or via Conda.

  2. Handle decoding and file errors

    main

    When working with audioread, be prepared to handle the following exceptions:

    • audioread.DecodeError: Raised when no available backend can successfully open the file (indicates an unsupported file type).
    • IOError: Raised if the file does not exist.
    • audioread.NoBackendError: Raised when a required external library or tool (like FFmpeg) is missing or has a broken installation.
  3. Specify backends for audio_open

    main

    By default, audioread.audio_open tries all available backends. You can restrict this by passing a second optional parameter to specify which backends to attempt.

    To see which backends are currently usable on your system, use the audioread.available_backends() function.

  4. Decode audio files with audioread.audio_open

    main

    Use audioread.audio_open(filename) to transparently select a backend capable of reading the specified audio file. The function returns an audio file object that can be used as a context manager.

    Iterating over the object yields buffers containing raw 16-bit little-endian signed integer PCM data. Each buffer is a bytes-like object (buffer, bytes, or bytearray).

    Supported backends include:

    • Gstreamer (via PyGObject)
    • Core Audio (on Mac OS X via ctypes)
    • MAD (via pymad)
    • FFmpeg or Libav (via CLI)
    • Standard library wave, aifc, and sunau (for uncompressed formats)
    import audioread
    
    with audioread.audio_open(filename) as f:
        print(f.channels, f.samplerate, f.duration)
        for buf in f:
            do_something(buf)
  5. Access audio file metadata

    main

    The object returned by audioread.audio_open provides the following metadata fields:

    • channels: The number of audio channels (integer).
    • samplerate: The sampling rate in Hz (integer).
    • duration: The length of the audio in seconds (float).
  6. Open an audio file with audio_open()

    main

    Use audio_open(path, backends=None) to open an audio file. If backends is not provided, the function automatically attempts to use all available backends on your system.

    To improve performance when opening many files, call available_backends() once and pass the resulting list to subsequent audio_open() calls to avoid repeated backend discovery costs.

    import audioread
    
    # Automatically try all available backends
    with audioread.audio_open('example.mp3') as f:
        print(f.filesize)
    
    # Optimized approach for multiple files
    backends = audioread.available_backends()
    for path in ['file1.mp3', 'file2.wav', 'file3.m4a']:
        try:
            with audioread.audio_open(path, backends=backends) as f:
                # process file
                pass
        except audioread.NoBackendError:
            print(f"Could not decode {path}")
  7. List available audio backends with available_backends()

    main

    The available_backends(flush_cache=False) function returns a list of audio file classes (backends) currently available on your system.

    • The list is cached after the first call to improve performance.
    • If you need to re-scan the system for new backends, call available_backends(flush_cache=True) to clear the cache and reconstruct the list.
    import audioread
    
    # Get all available backends
    backends = audioread.available_backends()
    print(f"Available backends: {backends}")
    
    # Force a refresh of the backend list
    backends = audioread.available_backends(flush_cache=True)
  8. Handle audio decoding errors

    main

    When working with audioread, you should be prepared to handle two specific exceptions:

    1. audioread.NoBackendError: Raised by audio_open() if none of the provided or available backends can successfully open the specified file.
    2. audioread.DecodeError: Raised by a backend if it encounters an error during the decoding process.
  9. Use the AudioFile base class

    main

    The AudioFile class serves as the base class for all audio file type implementations within audioread. While it is an abstract base class, it defines the interface that all specific audio format readers must follow to ensure compatibility with the library's high-level functions.

    from audioread import AudioFile
    
    # AudioFile is the base class for all audio file types.
  10. Handle decoding errors with DecodeError

    main

    When working with audioread, you should catch DecodeError to handle any issues related to the decoding process. This is the base exception class for all decoding errors raised by the package.

    from audioread import DecodeError
    
    try:
        # Attempt to read an audio file
        pass
    except DecodeError as e:
        print(f"Failed to decode audio: {e}")
  11. Handle missing backends with NoBackendError

    main

    NoBackendError is a subclass of DecodeError. It is raised when a file cannot be decoded because either no backends are installed/available in the environment, or every available backend attempted to decode the file and failed.

    from audioread import NoBackendError
    
    try:
        # Attempt to read an audio file that requires a specific backend
        pass
    except NoBackendError:
        print("No suitable audio backend found to decode this file.")