### Read and write example Source: https://github.com/bastibe/python-soundfile/blob/master/README.rst This example demonstrates how to read a wave file and copy it into a FLAC file. ```python import soundfile as sf data, samplerate = sf.read('existing_file.wav') sf.write('new_file.flac', data, samplerate) ``` -------------------------------- ### available_formats() Example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/format-utilities.md Demonstrates how to get and iterate through available audio formats. ```python import soundfile as sf formats = sf.available_formats() print(formats) # {'WAV': 'WAV (Microsoft)', 'FLAC': 'FLAC (FLAC Lossless Audio Codec)', # 'OGG': 'OGG (OGG Container format)', ...} for format_name, description in formats.items(): print(f"{format_name}: {description}") ``` -------------------------------- ### Read Mode Example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Opens an existing file for reading. ```python mode='r' # Read-only ``` -------------------------------- ### tell() example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Shows how to get the current read/write position before and after reading data. ```python with SoundFile('audio.wav') as f: print(f"Position: {f.tell()}") # Output: Position: 0 f.read(1024) print(f"Position: {f.tell()}") # Output: Position: 1024 ``` -------------------------------- ### Read/Write Mode Example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Opens an existing file for both reading and writing. ```python mode='r+' # Read and write to existing file ``` -------------------------------- ### Get basic file information Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/info.md This example demonstrates how to retrieve and print basic information about an audio file, such as sample rate, channels, duration, format, and subtype. ```python import soundfile as sf info = sf.info('audio.wav') print(f"Sample rate: {info.samplerate} Hz") print(f"Channels: {info.channels}") print(f"Duration: {info.duration:.2f} seconds") print(f"Format: {info.format} ({info.format_info})") print(f"Subtype: {info.subtype} ({info.subtype_info})") ``` -------------------------------- ### Bitrate Mode Examples Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Illustrates the use of the `bitrate_mode` parameter for variable-rate codecs like MP3, showing examples for 'CONSTANT', 'VARIABLE', and 'AVERAGE' modes. ```python import soundfile as sf import numpy as np # Generate test audio audio = np.random.randn(44100 * 5, 2) sr = 44100 # MP3 with constant bitrate sf.write('constant.mp3', audio, sr, bitrate_mode='CONSTANT', compression_level=0.8) # MP3 with variable bitrate (best quality) sf.write('quality.mp3', audio, sr, bitrate_mode='VARIABLE', compression_level=0.9) # MP3 with average bitrate sf.write('balanced.mp3', audio, sr, bitrate_mode='AVERAGE', compression_level=0.7) ``` -------------------------------- ### Explicit Format Example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Demonstrates setting the format explicitly, which has the highest priority. ```python import soundfile as sf # Explicit format (highest priority) with sf.SoundFile('data.bin', 'w', 44100, 2, format='WAV') as f: f.write(data) ``` -------------------------------- ### Install Sphinx and dependencies Source: https://github.com/bastibe/python-soundfile/blob/master/CONTRIBUTING.rst Command to install Sphinx and other necessary packages for building documentation. ```bash pip install -r doc/requirements.txt --user ``` -------------------------------- ### Virtual IO Example with BytesIO Source: https://github.com/bastibe/python-soundfile/blob/master/README.rst This example shows how to read audio data from an in-memory BytesIO object. ```python import soundfile as sf with open('filename.flac', 'rb') as f: data, samplerate = sf.read(f) ``` -------------------------------- ### flush() example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Demonstrates writing data and then flushing it to disk. ```python with SoundFile('output.wav', 'w', 44100, 2) as f: f.write(data) f.flush() # Ensure data is written to disk ``` -------------------------------- ### Mono Audio Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Example of creating mono audio files. ```python import soundfile as sf # Mono audio with sf.SoundFile('mono.wav', 'w', samplerate=44100, channels=1) as f: f.write(data) ``` -------------------------------- ### Write Mode Examples Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Opens a file for writing, with options to overwrite or create exclusively. ```python mode='w' # Write, overwrite if exists mode='w+' # Write and read, overwrite if exists mode='x' # Write, exclusive create (fail if exists) mode='x+' # Write and read, exclusive create (fail if exists) ``` -------------------------------- ### Get total frames for pre-allocation Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/info.md This example shows how to use `sf.info()` to get the total number of frames in a file, which can then be used to pre-allocate a NumPy array for efficient reading. ```python import soundfile as sf import numpy as np info = sf.info('large_audio.wav') # Pre-allocate array based on file size data = np.zeros((info.frames, info.channels), dtype='float32') # Now read into pre-allocated array sf.read('large_audio.wav', out=data) ``` -------------------------------- ### Virtual IO Example with HTTP Request Source: https://github.com/bastibe/python-soundfile/blob/master/README.rst This example demonstrates reading audio data directly from a URL using an HTTP request. ```python import io import soundfile as sf from urllib.request import urlopen url = "http://tinyurl.com/shepard-risset" data, samplerate = sf.read(io.BytesIO(urlopen(url).read())) ``` -------------------------------- ### Install coverage.py Source: https://github.com/bastibe/python-soundfile/blob/master/CONTRIBUTING.rst Command to install the coverage.py tool for measuring code coverage. ```bash pip install coverage --user ``` -------------------------------- ### Explicit Subtype Example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Shows how to specify a subtype explicitly, for example, 'PCM_24'. ```python # Explicit subtype with sf.SoundFile('audio.wav', 'w', 44100, 2, subtype='PCM_24') as f: f.write(data) ``` -------------------------------- ### RAW Audio (Minimal Format) Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Placeholder for an example demonstrating RAW audio format. ```python import soundfile as sf ``` -------------------------------- ### Auto-detected Format Example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Shows how the format is automatically detected from the file extension. ```python # Auto-detected from extension (most common) with sf.SoundFile('audio.wav', 'w', 44100, 2) as f: f.write(data) ``` -------------------------------- ### Default Subtype Example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Demonstrates using the default subtype for a format like WAV. ```python import soundfile as sf # Uses default PCM_16 for WAV with sf.SoundFile('audio.wav', 'w', 44100, 2) as f: f.write(data) ``` -------------------------------- ### String Representation Example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Example of printing a SoundFile object to get its string representation. ```python with SoundFile('audio.wav') as f: print(f) # Output: SoundFile('audio.wav', mode='r', samplerate=44100, channels=2, format='WAV', subtype='PCM_16', endian='FILE') ``` -------------------------------- ### SoundFile Object Example Source: https://github.com/bastibe/python-soundfile/blob/master/README.rst This example shows how to open a sound file as a SoundFile object and process it using a context manager. ```python import soundfile as sf with sf.SoundFile('myfile.wav', 'r+') as f: while f.tell() < f.frames: pos = f.tell() data = f.read(1024) f.seek(pos) f.write(data*2) ``` -------------------------------- ### RAW File Reading Example Source: https://github.com/bastibe/python-soundfile/blob/master/README.rst This example demonstrates how to read a RAW audio file with specified parameters. ```python import soundfile as sf data, samplerate = sf.read('myfile.raw', channels=1, samplerate=44100, subtype='FLOAT') ``` -------------------------------- ### Compare file formats Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/info.md This example demonstrates how to compare the properties (sample rate and channels) of two different audio files to check for compatibility. ```python import soundfile as sf # Compare two files info1 = sf.info('file1.wav') info2 = sf.info('file2.flac') # Check if they're compatible for processing together if info1.samplerate != info2.samplerate: print(f"Sample rate mismatch: {info1.samplerate} vs {info2.samplerate}") if info1.channels != info2.channels: print(f"Channel mismatch: {info1.channels} vs {info2.channels}") ``` -------------------------------- ### Block Processing Example Source: https://github.com/bastibe/python-soundfile/blob/master/README.rst This example calculates the signal level for each block of a long file. ```python import numpy as np import soundfile as sf rms = [np.sqrt(np.mean(block**2)) for block in sf.blocks('myfile.wav', blocksize=1024, overlap=512)] ``` -------------------------------- ### Get verbose information Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/info.md This example retrieves extended technical details about the audio file by setting the `verbose` parameter to `True`. The output includes endianness, section count, frame count, and extra information. ```python import soundfile as sf info = sf.info('audio.wav', verbose=True) print(info) # Shows endian, sections, frames, and extra_info ``` -------------------------------- ### Set up local environment Source: https://github.com/bastibe/python-soundfile/blob/master/CONTRIBUTING.rst Commands to install necessary packages and set up the local development environment for testing. ```bash pip install numpy pytest "cffi>=1.0" typing-extensions python soundfile_build.py ``` -------------------------------- ### Format from File Header Example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Illustrates retrieving the format from the file header when reading a file with an unknown extension. ```python # From file header (read mode) with sf.SoundFile('unknown_extension.snd', 'r') as f: print(f.format) # Retrieved from file header ``` -------------------------------- ### write() example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Illustrates writing NumPy array data to a WAV file. ```python import numpy as np with SoundFile('output.wav', 'w', 44100, 2) as f: # Generate 2 seconds of stereo noise data = np.random.randn(88200, 2) f.write(data) ``` -------------------------------- ### Find a format that supports a specific subtype Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/format-utilities.md This example shows how to find all audio formats that support a given subtype, using 'VORBIS' as an example. ```python import soundfile as sf target_subtype = 'VORBIS' all_formats = sf.available_formats() all_subtypes = sf.available_subtypes() compatible_formats = [] for format_name in all_formats.keys(): if sf.check_format(format_name, target_subtype): compatible_formats.append(format_name) print(f"{target_subtype} is supported by: {compatible_formats}") # Output: VORBIS is supported by: ['OGG'] ``` -------------------------------- ### Inspect multiple files Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/info.md This example shows how to iterate through a directory, identify WAV files, and print their duration and sample rate using `sf.info()`. ```python import soundfile as sf import os audio_dir = './audio_files' for filename in os.listdir(audio_dir): if filename.endswith('.wav'): filepath = os.path.join(audio_dir, filename) info = sf.info(filepath) print(f"{filename}: {info.duration:.1f}s @ {info.samplerate} Hz, {info.channels}ch") ``` -------------------------------- ### seek() example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Demonstrates seeking to the beginning, forward from the current position, and from the end of the file. ```python with SoundFile('audio.wav') as f: # Seek to beginning f.seek(0) # Seek forward 4096 frames from current position f.seek(4096, SEEK_CUR) # Seek to 1 second before end f.seek(-44100, SEEK_END) ``` -------------------------------- ### read() examples Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Illustrates reading a specific number of frames, reading the entire file, and reading into a pre-allocated NumPy array. ```python with SoundFile('stereo.wav') as f: # Read 1024 frames as float64 block = f.read(1024) # Read entire file as int16 f.seek(0) all_data = f.read(dtype='int16') # Read with pre-allocated array import numpy as np output = np.zeros((4096, 2), dtype='float32') f.seek(0) f.read(out=output) ``` -------------------------------- ### Endianness Examples Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Shows how to specify the `endian` parameter, which is primarily relevant for RAW audio files, demonstrating 'FILE', 'LITTLE', and 'BIG' endianness. ```python import soundfile as sf # Default (recommended) with sf.SoundFile('audio.wav', 'w', 44100, 2) as f: f.write(data) # Explicit endianness for WAV with sf.SoundFile('audio.wav', 'w', 44100, 2, endian='LITTLE') as f: f.write(data) # RAW file with specific endianness with sf.SoundFile('audio.raw', 'w', 44100, 2, format='RAW', subtype='PCM_16', endian='BIG') as f: f.write(data) ``` -------------------------------- ### Example 1: File not found Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/errors.md Demonstrates catching a LibsndfileError when a file does not exist. ```python try: data, sr = sf.read('nonexistent.wav') except sf.LibsndfileError as e: print(f"Error code: {e.code}") print(f"Error message: {e.error_string}") print(f"Full error: {e}") ``` -------------------------------- ### buffer_read_into() example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Shows how to read audio data directly into a pre-allocated bytearray or memoryview. ```python import array with SoundFile('audio.wav') as f: buf = array.array('f', [0] * (4096 * 2)) frames_read = f.buffer_read_into(buf, 'float32') ``` -------------------------------- ### buffer_write() example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Demonstrates writing audio data from a buffer or bytes object to a WAV file. ```python import array audio_data = array.array('f', [0.1, -0.2, 0.3, -0.4]) with SoundFile('output.wav', 'w', 44100, 1) as f: f.buffer_write(audio_data, 'float32') ``` -------------------------------- ### RAW Format with Explicit Subtype Example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Highlights that the RAW format requires the subtype to be explicitly specified. ```python # RAW requires explicit subtype with sf.SoundFile('audio.raw', 'w', 44100, 2, format='RAW', subtype='PCM_16') as f: f.write(data) ``` -------------------------------- ### check_format() Examples Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/format-utilities.md Illustrates how to check the validity of format, subtype, and endianness combinations. ```python import soundfile as sf # Valid combinations sf.check_format('WAV', 'PCM_16') # True sf.check_format('FLAC', 'PCM_24') # True sf.check_format('OGG', 'VORBIS') # True # Invalid combinations sf.check_format('FLAC', 'VORBIS') # False (VORBIS is for OGG) sf.check_format('WAV', 'INVALID_SUBTYPE') # False # Check with endianness sf.check_format('WAV', 'PCM_16', 'LITTLE') # True sf.check_format('WAV', 'PCM_16', 'INVALID') # False ``` -------------------------------- ### Read with Format Validation Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Example of reading an audio file by explicitly specifying the format, useful for non-standard file extensions. ```python import soundfile as sf # Explicitly specify format for non-standard extensions with sf.SoundFile('audio.snd', 'r', format='WAV') as f: print(f"Sample rate: {f.samplerate}") print(f"Channels: {f.channels}") data = f.read() ``` -------------------------------- ### available_subtypes() Examples Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/format-utilities.md Shows how to retrieve all available subtypes and filter them by a specific format. ```python import soundfile as sf # Get all available subtypes all_subtypes = sf.available_subtypes() print(all_subtypes) # {'PCM_16': 'Signed 16 bit PCM', 'PCM_24': 'Signed 24 bit PCM', # 'FLOAT': '32 bit float', 'VORBIS': 'Xiph Vorbis encoding', ...} # Get subtypes for FLAC format only flac_subtypes = sf.available_subtypes('FLAC') print(flac_subtypes) # {'PCM_16': 'Signed 16 bit PCM', 'PCM_24': 'Signed 24 bit PCM', # 'PCM_S8': 'Signed 8 bit PCM'} # Get subtypes for WAV wav_subtypes = sf.available_subtypes('WAV') # Case-insensitive subtypes = sf.available_subtypes('flac') # Works the same as 'FLAC' ``` -------------------------------- ### Context Manager Example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Shows how to use SoundFile as a context manager for automatic file closing. ```python with SoundFile('audio.wav') as f: data = f.read() # File is automatically closed here ``` -------------------------------- ### Metadata Access Example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Demonstrates reading and writing metadata attributes of a SoundFile object. ```python with SoundFile('audio.wav') as f: # Read metadata print(f.title) print(f.artist) # Write metadata with SoundFile('output.wav', 'w', 44100, 2) as f: f.title = "My Song" f.artist = "My Name" f.album = "My Album" f.write(data) ``` -------------------------------- ### buffer_read() example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Demonstrates reading audio data into a memoryview object without NumPy conversion. ```python with SoundFile('audio.wav') as f: buf = f.buffer_read(1024, 'float32') # Process buffer without NumPy overhead ``` -------------------------------- ### Streaming Audio (MP3) Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Example of creating MP3 audio with a constant bitrate for consistent streaming, using a specified compression level. ```python import soundfile as sf # MP3 with constant bitrate for consistent streaming with sf.SoundFile('audio.mp3', 'w', samplerate=44100, channels=2, compression_level=0.8, bitrate_mode='CONSTANT') as f: f.write(data) ``` -------------------------------- ### Python 2.x HTTP Request Example Source: https://github.com/bastibe/python-soundfile/blob/master/README.rst This is the Python 2.x equivalent for reading audio data from a URL. ```python from urllib2 import urlopen ``` -------------------------------- ### Type Checking with pyright Source: https://github.com/bastibe/python-soundfile/blob/master/CONTRIBUTING.rst Commands to install pyright and check types in the soundfile.py file. ```bash pip install pyright pyright soundfile.py ``` -------------------------------- ### Controlling bitrate mode and compression level Source: https://github.com/bastibe/python-soundfile/blob/master/README.rst Examples demonstrating how to control bitrate mode and compression level when writing MP3 files. ```python import soundfile as sf # for example, this uncompressed 5 minute wav file with 32 kHz sample rate is 18 Mb data, samplerate = sf.read('5min_32kHz.wav') # maximum mp3 compression results in 1.1 Mb file, with either CONSTANT or VARIABLE bit rate sf.write('max_compression_vbr.mp3', data, samplerate, bitrate_mode='VARIABLE', compression_level=.99) sf.write('max_compression_cbr.mp3', data, samplerate, bitrate_mode='CONSTANT', compression_level=.99) # minimum mp3 compression results in 3.5 Mb file sf.write('min_compression_vbr.mp3', data, samplerate, bitrate_mode='VARIABLE', compression_level=0) ``` -------------------------------- ### Format Queries Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/INDEX.md Examples of querying available audio formats and subtypes supported by the library, and iterating through their descriptions. ```python import soundfile as sf # List all supported formats for fmt, desc in sf.available_formats().items(): print(f"{fmt}: {desc}") # List subtypes for a format for subtype, desc in sf.available_subtypes('WAV').items(): print(f"{subtype}: {desc}") ``` -------------------------------- ### Virtual IO Example with HTTP Request (Python 2.x) Source: https://github.com/bastibe/python-soundfile/blob/master/doc/index.md Reads audio data from a URL using an HTTP request and BytesIO for Python 2.x. ```python from urllib2 import urlopen import io import soundfile as sf url = "http://tinyurl.com/shepard-risset" data, samplerate = sf.read(io.BytesIO(urlopen(url).read())) ``` -------------------------------- ### Type Hinting with FileDescriptorOrPath Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/types.md Example showing how to use sf.FileDescriptorOrPath for type hinting, allowing various file sources for loading audio. ```python import soundfile as sf from pathlib import Path def load_audio(file: sf.FileDescriptorOrPath) -> tuple[sf.AudioData, int]: """Load audio from various file sources.""" return sf.read(file) # All of these work load_audio('audio.wav') load_audio(Path('audio.wav')) load_audio(3) # file descriptor with open('audio.wav', 'rb') as f: load_audio(f) ``` -------------------------------- ### High-Quality Audio Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Example of creating high-quality audio files with a samplerate of 48 kHz, 24-bit depth, and stereo channels. ```python import soundfile as sf # High-quality: 48 kHz, 24-bit, stereo with sf.SoundFile('audio.wav', 'w', samplerate=48000, channels=2, subtype='PCM_24') as f: f.write(data) ``` -------------------------------- ### Display formatted information Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/info.md This example shows how to print the `info` object directly, which utilizes its `__repr__` method for a nicely formatted output. ```python import soundfile as sf info = sf.info('audio.wav') print(info) # Uses __repr__ for nice formatting ``` -------------------------------- ### RAW format requires explicit specification Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Example of writing a RAW audio file with explicit format, subtype, and endianness. ```python with sf.SoundFile('audio.raw', 'w', samplerate=44100, channels=2, format='RAW', subtype='PCM_16', endian='LITTLE') as f: f.write(data) ``` -------------------------------- ### Type Hinting with AudioData Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/types.md Example demonstrating how to use sf.AudioData for type hinting, showing processing of mono and stereo audio. ```python from typing import Union import soundfile as sf import numpy as np def process_audio(data: sf.AudioData, sr: int) -> sf.AudioData: """Process audio data and return modified version.""" # Can handle any shape and supported dtype return data * 0.8 # Scale audio # Works with 1D mono = np.random.randn(44100) result = process_audio(mono, 44100) # Works with 2D stereo = np.random.randn(44100, 2) result = process_audio(stereo, 44100) ``` -------------------------------- ### CD-Quality Audio (Standard) Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Example of creating CD-quality audio files with a samplerate of 44.1 kHz, 16-bit depth, and stereo channels. ```python import soundfile as sf # CD-quality: 44.1 kHz, 16-bit, stereo with sf.SoundFile('audio.wav', 'w', samplerate=44100, channels=2, subtype='PCM_16') as f: f.write(data) ``` -------------------------------- ### Basic Usage Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/README.md Demonstrates basic reading, writing, and getting file information using the soundfile library. ```python import soundfile as sf # Read audio data, samplerate = sf.read('audio.wav') # Write audio sf.write('output.wav', data, samplerate) # Get file info info = sf.info('audio.wav') print(f"Duration: {info.duration:.2f}s") ``` -------------------------------- ### default_subtype() Examples Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/format-utilities.md Demonstrates how to find the default subtype for various audio formats, including case-insensitivity and formats with no default. ```python import soundfile as sf # Common formats with defaults sf.default_subtype('WAV') # 'PCM_16' sf.default_subtype('FLAC') # 'PCM_16' sf.default_subtype('OGG') # 'VORBIS' sf.default_subtype('MP3') # 'MPEG_LAYER_III' sf.default_subtype('MAT5') # 'DOUBLE' # RAW format has no default sf.default_subtype('RAW') # None # Case-insensitive sf.default_subtype('wav') # 'PCM_16' sf.default_subtype('FlAc') # 'PCM_16' ``` -------------------------------- ### Get default subtype Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/INDEX.md Retrieves the default subtype for a given audio format, for example, 'VORBIS' for 'OGG'. ```python # Get default subtype default = sf.default_subtype('OGG') # 'VORBIS' ``` -------------------------------- ### Compression Level Examples Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Demonstrates how to use the `compression_level` parameter for different formats like FLAC, OGG, and MP3. It also shows that the parameter is ignored for formats like WAV that do not support compression. ```python import soundfile as sf import numpy as np # Generate test audio audio = np.random.randn(44100 * 5, 2) # 5 seconds, stereo sr = 44100 # FLAC with high compression sf.write('compressed.flac', audio, sr, compression_level=0.9) # OGG with medium compression sf.write('audio.ogg', audio, sr, compression_level=0.5) # MP3 with maximum compression sf.write('small.mp3', audio, sr, compression_level=1.0) # WAV doesn't support compression (parameter ignored) sf.write('lossless.wav', audio, sr, compression_level=0.8) # Ignored ``` -------------------------------- ### Example 2: Invalid format combination Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/errors.md Shows how to catch a LibsndfileError when attempting to write an incompatible format (e.g., VORBIS to WAV). ```python try: sf.write('output.wav', data, 44100, subtype='VORBIS') # VORBIS is not compatible with WAV except sf.LibsndfileError as e: print(f"Invalid format: {e.error_string}") ``` -------------------------------- ### Example 3: Missing RAW file parameters Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/errors.md Illustrates catching LibsndfileError or TypeError when reading a RAW file without specifying samplerate and channels. ```python try: data, sr = sf.read('audio.raw') # Missing samplerate and channels except (sf.LibsndfileError, TypeError) as e: print(f"Error: {e}") ``` -------------------------------- ### truncate() example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Example of truncating an audio file to a specific number of frames. ```python with SoundFile('audio.wav', 'r+') as f: # Keep only first 44100 frames (1 second at 44.1kHz) f.truncate(44100) ``` -------------------------------- ### SoundFile Constructor Examples Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Demonstrates various ways to open and use the SoundFile class for reading, writing, and read/write operations, including the use of context managers. ```python from soundfile import SoundFile # Read-only f = SoundFile('audio.wav') f.close() # Write new file with context manager with SoundFile('output.wav', 'w', 44100, 2) as f: # f.write(data) pass # Read/write existing file with SoundFile('audio.wav', 'r+') as f: data = f.read(1024) f.seek(0) f.write(data) # Create new file, fail if exists with SoundFile('unique.wav', 'x', 44100, 2) as f: pass # File creation with exclusive mode ``` -------------------------------- ### ValueError Example: Invalid format Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/errors.md Example of catching a ValueError when an unknown format name is provided. ```python # Invalid format try: sf.write('output.wav', data, 44100, format='INVALID') except ValueError as e: print(f"Invalid format: {e}") ``` -------------------------------- ### ValueError Example: Invalid dtype Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/errors.md Example of catching a ValueError when an unsupported dtype string is used. ```python import soundfile as sf # Invalid dtype try: data, sr = sf.read('audio.wav', dtype='float128') except ValueError as e: print(f"Invalid dtype: {e}") ``` -------------------------------- ### TypeError Example: Invalid mode Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/errors.md Example of catching a TypeError when an invalid type is provided for the 'mode' parameter. ```python # Invalid mode try: with sf.SoundFile('audio.wav', mode=123) as f: pass except TypeError as e: print(f"Invalid mode: {e}") ``` -------------------------------- ### OSError Example: Permission denied Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/errors.md Example of catching an OSError when attempting to write to a file without sufficient permissions. ```python import soundfile as sf # Permission denied try: sf.write('/root/audio.wav', data, 44100) except OSError as e: print(f"Permission denied: {e}") ``` -------------------------------- ### TypeError Example: Missing samplerate Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/errors.md Example of catching a TypeError when the required 'samplerate' parameter is missing during file write. ```python import soundfile as sf # Missing samplerate try: with sf.SoundFile('output.wav', 'w', channels=2) as f: pass # samplerate is required except TypeError as e: print(f"Missing parameter: {e}") ``` -------------------------------- ### Inspect format details Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/info.md This example retrieves verbose information about an audio file and prints specific format details, including format, subtype, endianness, and any extra format-specific information. ```python import soundfile as sf info = sf.info('audio.mp3', verbose=True) print(f"Format: {info.format} - {info.format_info}") print(f"Subtype: {info.subtype} - {info.subtype_info}") print(f"Endianness: {info.endian}") if hasattr(info, 'extra_info') and info.extra_info: print(f"Extra info: {info.extra_info}") ``` -------------------------------- ### File Descriptor Management Examples Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Demonstrates the use of the `closefd` parameter when opening files using file descriptors, illustrating both default behavior (closing the descriptor) and manual closing. ```python import soundfile as sf import os # Open file, get file descriptor fd = os.open('audio.wav', os.O_RDONLY | os.O_BINARY) # Open with SoundFile, closefd=True (default) with sf.SoundFile(fd, closefd=True) as f: data = f.read() # fd is automatically closed here # Open with closefd=False fd = os.open('audio.wav', os.O_RDONLY | os.O_BINARY) with sf.SoundFile(fd, closefd=False) as f: data = f.read() # fd is NOT closed here; must close manually os.close(fd) ``` -------------------------------- ### ValueError Example: Compression level out of range Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/errors.md Example of catching a ValueError when the compression level is outside the valid range [0, 1]. ```python # Compression level out of range try: sf.write('output.flac', data, 44100, compression_level=2.0) except ValueError as e: print(f"Invalid compression level: {e}") ``` -------------------------------- ### OSError Example: Exclusive create, file exists Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/errors.md Example of catching an OSError when trying to create a file exclusively ('x' mode) that already exists. ```python # Exclusive create, file exists try: with sf.SoundFile('existing.wav', 'x') as f: pass except OSError as e: print(f"File exists: {e}") ``` -------------------------------- ### Check Format Combinations Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/configuration.md Demonstrates how to check if a format/subtype combination is valid and how to retrieve available subtypes for a format. ```python import soundfile as sf # Check if format/subtype combination is valid if sf.check_format('FLAC', 'PCM_24'): print("Valid combination") else: print("Invalid combination") # Get available subtypes for a format subtypes = sf.available_subtypes('WAV') print(subtypes) # Get default subtype default = sf.default_subtype('FLAC') print(default) # Output: PCM_16 ``` -------------------------------- ### Get file info Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/INDEX.md Retrieves and prints detailed information about an audio file, including duration, sample rate, channels, format, and subtype. It also shows how to get verbose information. ```python import soundfile as sf # Get file info info = sf.info('audio.wav') print(f"Duration: {info.duration:.2f}s") print(f"Sample rate: {info.samplerate} Hz") print(f"Channels: {info.channels}") print(f"Format: {info.format} ({info.format_info})") print(f"Subtype: {info.subtype} ({info.subtype_info})") # Verbose info info = sf.info('audio.wav', verbose=True) print(info) # Includes extra details ``` -------------------------------- ### SoundFileError Usage Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/errors.md Example of catching a generic SoundFileError. ```python import soundfile as sf try: data, sr = sf.read('audio.wav') except sf.SoundFileError as e: print(f"Soundfile error: {e}") ``` -------------------------------- ### Programmatically check file properties Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/info.md This example illustrates how to use the information obtained from `sf.info()` to programmatically check various properties of an audio file, such as the number of channels, duration, and sample rate. ```python import soundfile as sf info = sf.info('audio.wav') # Check if file is stereo if info.channels == 2: print("This is a stereo file") # Check if file is longer than 1 minute if info.duration > 60: print("File is longer than 1 minute") # Check sample rate if info.samplerate == 44100: print("CD quality (44.1 kHz)") elif info.samplerate == 48000: print("Professional audio (48 kHz)") ``` -------------------------------- ### copy_metadata() example Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Retrieves and prints metadata from an audio file. ```python with SoundFile('audio.wav') as f: metadata = f.copy_metadata() print(f"Title: {metadata.get('title', 'N/A')}") print(f"Artist: {metadata.get('artist', 'N/A')}") ``` -------------------------------- ### blocks() generator Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Example of using the blocks() generator to read audio in chunks. ```python with SoundFile('audio.wav') as f: for block in f.blocks(blocksize=2048, overlap=512): print(f"Block shape: {block.shape}") ``` -------------------------------- ### Context Manager Equivalent Source: https://github.com/bastibe/python-soundfile/blob/master/_autodocs/api-reference/soundfile.md Illustrates the equivalent code without using the 'with' statement. ```python f = SoundFile('audio.wav') try: data = f.read() finally: f.close() ``` -------------------------------- ### Build documentation Source: https://github.com/bastibe/python-soundfile/blob/master/CONTRIBUTING.rst Command to re-create the HTML documentation pages locally using Sphinx. ```bash python setup.py build_sphinx ```