### Install documentation dependencies Source: https://python-soundfile.readthedocs.io Install the required packages for building the project documentation. ```bash pip install -r doc/requirements.txt --user ``` -------------------------------- ### Initialize SoundFile Source: https://python-soundfile.readthedocs.io Example of importing the necessary modules and initializing a SoundFile object. ```python >>> import numpy as np >>> from soundfile import SoundFile >>> myfile = SoundFile('stereo_file.wav') ``` -------------------------------- ### Install coverage.py Source: https://python-soundfile.readthedocs.io Install the coverage tool to measure code execution during tests. ```bash pip install coverage --user ``` -------------------------------- ### Set up local development environment Source: https://python-soundfile.readthedocs.io Install the necessary dependencies and build the soundfile extension. ```bash pip install numpy pytest "cffi>=1.0" python soundfile_build.py ``` -------------------------------- ### Initialize SoundFile for reading Source: https://python-soundfile.readthedocs.io Setup the SoundFile object to perform read operations. ```python >>> from soundfile import SoundFile >>> myfile = SoundFile('stereo_file.wav') ``` -------------------------------- ### Initialize SoundFile for seeking Source: https://python-soundfile.readthedocs.io Setup the SoundFile object to perform seek operations. ```python >>> from soundfile import SoundFile, SEEK_END >>> myfile = SoundFile('stereo_file.wav') ``` -------------------------------- ### Python 2.x compatibility for URL reading Source: https://python-soundfile.readthedocs.io Replacement import for the URL reading example when using Python 2.x. ```python from urllib2 import urlopen ``` -------------------------------- ### Read file in blocks Source: https://python-soundfile.readthedocs.io Example of using the blocks generator to read an audio file in chunks of 1024 frames. ```python >>> from soundfile import SoundFile >>> with SoundFile('stereo_file.wav') as f: >>> for block in f.blocks(blocksize=1024): >>> pass # do something with 'block' ``` -------------------------------- ### Seek to the beginning of the file Source: https://python-soundfile.readthedocs.io Move the read/write position to the start of the file. ```python >>> myfile.seek(0) 0 ``` -------------------------------- ### soundfile.blocks Source: https://python-soundfile.readthedocs.io Returns a generator for block-wise reading of an audio file. Iteration starts at the beginning and stops at the end of the file by default, with options to start later and stop earlier. ```APIDOC ## soundfile.blocks ### Description Returns a generator for block-wise reading of an audio file. By default, iteration starts at the beginning and stops at the end of the file. Use start to start at a later position and frames or stop to stop earlier. ### Method Function call ### Endpoint soundfile.blocks(file, blocksize=None, overlap=0, frames=-1, start=0, stop=None, dtype='float64', always_2d=False, fill_value=None, out=None, samplerate=None, channels=None, format=None, subtype=None, endian=None, closefd=True) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (str or int or file-like object) - Required - The file to read from. - **blocksize** (int) - Required - The number of frames to read per block. Either this or out must be given. - **overlap** (int, optional) - Optional - The number of frames to rewind between each block. - **frames** - Optional - See read(). - **start** - Optional - See read(). - **stop** - Optional - See read(). - **dtype** ({'float64','float32','int32','int16'}, optional) - Optional - See read(). - **always_2d** - Optional - See read(). - **fill_value** - Optional - See read(). - **out** - Optional - See read(). - **samplerate** - Optional - See SoundFile. - **channels** - Optional - See SoundFile. - **format** - Optional - See SoundFile. - **subtype** - Optional - See SoundFile. - **endian** - Optional - See SoundFile. - **closefd** - Optional - See SoundFile. ### Request Example ```python import soundfile as sf for block in sf.blocks('stereo_file.wav', blocksize=1024): pass # do something with 'block' ``` ### Response #### Success Response Yields numpy.ndarray or type(out) - Blocks of audio data. If out was given, and the requested frames are not an integer multiple of the length of out, and no fill_value was given, the last block will be a smaller view into out. #### Response Example None ``` -------------------------------- ### Write random data to a file Source: https://python-soundfile.readthedocs.io Example of writing 10 frames of random data to a new stereo file using the write method. ```python >>> with SoundFile('stereo_file.wav', 'w', 44100, 2, 'PCM_24') as f: >>> f.write(np.random.randn(10, 2)) ``` -------------------------------- ### soundfile.read() Source: https://python-soundfile.readthedocs.io Reads audio data from a sound file and returns it as a NumPy array along with the sample rate. Supports specifying start position, number of frames, data type, and output array. ```APIDOC ## soundfile.read() ### Description Reads audio data from a sound file and returns it as a NumPy array along with the sample rate. Supports specifying start position, number of frames, data type, and output array. ### Method Function call ### Signature soundfile.read(file, frames=-1, start=0, stop=None, dtype='float64', always_2d=False, fill_value=None, out=None, samplerate=None, channels=None, format=None, subtype=None, endian=None, closefd=True) ### Parameters - **file** (str or int or file-like object) - Required - The file to read from. See SoundFile for details. - **frames** (int, optional) - The number of frames to read. If frames is negative, the whole rest of the file is read. Not allowed if stop is given. - **start** (int, optional) - Where to start reading. A negative value counts from the end. - **stop** (int, optional) - The index after the last frame to be read. A negative value counts from the end. Not allowed if frames is given. - **dtype** ({'float64', 'float32', 'int32', 'int16'}, optional) - Data type of the returned array, by default 'float64'. Floating point audio data is typically in the range from -1.0 to 1.0. Integer data is in the range from -2**15 to 2**15-1 for 'int16' and from -2**31 to 2**31-1 for 'int32'. - **always_2d** (bool, optional) - By default, reading a mono sound file will return a one-dimensional array. With always_2d=True, audio data is always returned as a two-dimensional array, even if the audio file has only one channel. - **fill_value** (float, optional) - If more frames are requested than available in the file, the rest of the output is filled with fill_value. If fill_value is not specified, a smaller array is returned. - **out** (numpy.ndarray or subclass, optional) - If out is specified, the data is written into the given array instead of creating a new array. In this case, the arguments dtype and always_2d are silently ignored! If frames is not given, it is obtained from the length of out. - **samplerate** - See SoundFile. - **channels** - See SoundFile. - **format** - See SoundFile. - **subtype** - See SoundFile. - **endian** - See SoundFile. - **closefd** - See SoundFile. ### Returns - **audiodata** (numpy.ndarray or type(out)) - A two-dimensional (frames x channels) NumPy array is returned. If the sound file has only one channel, a one-dimensional array is returned. Use always_2d=True to return a two-dimensional array anyway. If out was specified, it is returned. If out has more frames than available in the file (or if frames is smaller than the length of out) and no fill_value is given, then only a part of out is overwritten and a view containing all valid frames is returned. - **samplerate** (int) - The sample rate of the audio file. ### Example ```python >>> import soundfile as sf >>> data, samplerate = sf.read('stereo_file.wav') >>> data array([[ 0.71329652, 0.06294799], [-0.26450912, -0.38874483], ... [ 0.67398441, -0.11516333]]) >>> samplerate 44100 ``` ``` -------------------------------- ### SoundFile.__init__ Source: https://python-soundfile.readthedocs.io Opens a sound file with the specified parameters. The constructor accepts a file path, descriptor, or file-like object, and optional parameters for mode, sample rate, channels, subtype, endian, format, closefd, compression level, and bitrate mode. ```APIDOC ## SoundFile.__init__ ### Description Opens a sound file. If opened with mode 'r' or 'r+', sample rate, channels, and format are obtained from the file, except for 'RAW' data format. The object is a context manager, so close() is called automatically when used in a with statement. ### Method Constructor ### Signature SoundFile(file, mode='r', samplerate=None, channels=None, subtype=None, endian=None, format=None, closefd=True, compression_level=None, bitrate_mode=None) ### Parameters - **file** (str or int or file-like object) - Required - The file to open. Can be a file name, file descriptor, or a Python file object with read()/readinto(), write(), seek(), and tell() methods. - **mode** ({'r','r+','w','w+','x','x+'}, optional) - Open mode. Must begin with 'r' (read), 'w' (write, truncates), or 'x' (write, raises error if file exists). May contain '+' for both reading and writing. 'b' for binary mode is implied. - **samplerate** (int) - Optional - The sample rate of the file. If mode contains 'r', obtained from the file (except for 'RAW' files). - **channels** (int) - Optional - The number of channels. If mode contains 'r', obtained from the file (except for 'RAW' files). - **subtype** (str, sometimes optional) - The subtype of the sound file. If mode contains 'r', obtained from the file (except for 'RAW' files); otherwise default depends on format. - **endian** ({'FILE','LITTLE','BIG','CPU'}, sometimes optional) - The endian-ness. If mode contains 'r', obtained from the file (except for 'RAW' files); otherwise default is 'FILE'. - **format** (str, sometimes optional) - The major format. If mode contains 'r', obtained from the file (except for 'RAW' files); otherwise determined from file extension. - **closefd** (bool, optional) - Whether to close the file descriptor on close(). Only applicable if file is a file descriptor. - **compression_level** (float, optional) - Compression level on write(), between 0.0 and 1.0. - **bitrate_mode** ({'CONSTANT','AVERAGE','VARIABLE'}, optional) - Bitrate mode on write(). ### Examples ```python >>> from soundfile import SoundFile >>> myfile = SoundFile('existing_file.wav') >>> # do something with myfile >>> myfile.close() >>> with SoundFile('new_file.wav', 'x+', 44100, 2) as myfile: >>> # do something with myfile >>> assert not myfile.closed >>> assert myfile.closed ``` ``` -------------------------------- ### Build documentation with Sphinx Source: https://python-soundfile.readthedocs.io Generate the HTML documentation pages locally. ```bash python setup.py build_sphinx ``` -------------------------------- ### Import SoundFile Source: https://python-soundfile.readthedocs.io Import the SoundFile class to begin working with sound files. ```python >>> from soundfile import SoundFile ``` -------------------------------- ### Get default subtype using sf.default_subtype Source: https://python-soundfile.readthedocs.io Returns the default subtype for a given audio format. ```python >>> import soundfile as sf >>> sf.default_subtype('WAV') 'PCM_16' >>> sf.default_subtype('MAT5') 'DOUBLE' ``` -------------------------------- ### Read and write audio files with soundfile.read and soundfile.write Source: https://python-soundfile.readthedocs.io Reads an existing WAV file and copies its content into a new FLAC file. ```python import soundfile as sf data, samplerate = sf.read('existing_file.wav') sf.write('new_file.flac', data, samplerate) ``` -------------------------------- ### Create a New File with a Context Manager Source: https://python-soundfile.readthedocs.io Create a new sound file using a with statement, which ensures the file is automatically closed after the block finishes. ```python >>> with SoundFile('new_file.wav', 'x+', 44100, 2) as myfile: >>> # do something with myfile >>> # ... >>> assert not myfile.closed >>> # myfile.close() is called automatically at the end >>> assert myfile.closed ``` -------------------------------- ### Retrieve available formats using sf.available_formats Source: https://python-soundfile.readthedocs.io Returns a dictionary of supported major audio formats. ```python >>> import soundfile as sf >>> sf.available_formats() {'FLAC': 'FLAC (FLAC Lossless Audio Codec)', 'OGG': 'OGG (OGG Container format)', 'WAV': 'WAV (Microsoft)', 'AIFF': 'AIFF (Apple/SGI)', ... 'WAVEX': 'WAVEX (Microsoft)', 'RAW': 'RAW (header-less)', 'MAT5': 'MAT5 (GNU Octave 2.1 / Matlab 5.0)'} ``` -------------------------------- ### Read from file-like objects Source: https://python-soundfile.readthedocs.io Use soundfile.read() with open file-like objects just as you would with regular file paths. ```python import soundfile as sf with open('filename.flac', 'rb') as f: data, samplerate = sf.read(f) ``` -------------------------------- ### soundfile.available_formats Source: https://python-soundfile.readthedocs.io Returns a dictionary of available major formats. ```APIDOC ## soundfile.available_formats ### Description Returns a dictionary of available major formats. ### Method Function call ### Endpoint soundfile.available_formats() ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import soundfile as sf sf.available_formats() ``` ### Response #### Success Response Returns a dictionary of available major formats. #### Response Example ```python {'FLAC': 'FLAC (FLAC Lossless Audio Codec)', 'OGG': 'OGG (OGG Container format)', 'WAV': 'WAV (Microsoft)', 'AIFF': 'AIFF (Apple/SGI)', ... 'WAVEX': 'WAVEX (Microsoft)', 'RAW': 'RAW (header-less)', 'MAT5': 'MAT5 (GNU Octave 2.1 / Matlab 5.0)'} ``` ``` -------------------------------- ### Manage SoundFile objects with context managers Source: https://python-soundfile.readthedocs.io Opens a sound file as a SoundFile object and uses a context manager to read and modify data in blocks. ```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) ``` -------------------------------- ### Run branch coverage analysis Source: https://python-soundfile.readthedocs.io Execute tests with branch coverage tracking and generate an HTML report. ```bash coverage run --branch --source soundfile -m pytest coverage html ``` -------------------------------- ### soundfile.available_subtypes Source: https://python-soundfile.readthedocs.io Returns a dictionary of available subtypes. If a format is given, only compatible subtypes are returned. ```APIDOC ## soundfile.available_subtypes ### Description Returns a dictionary of available subtypes. If a format is given, only compatible subtypes are returned. ### Method Function call ### Endpoint soundfile.available_subtypes(format=None) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **format** (str) - Optional - If given, only compatible subtypes are returned. ### Request Example ```python import soundfile as sf sf.available_subtypes('FLAC') ``` ### Response #### Success Response Returns a dictionary of available subtypes. #### Response Example ```python {'PCM_24': 'Signed 24 bit PCM', 'PCM_16': 'Signed 16 bit PCM', 'PCM_S8': 'Signed 8 bit PCM'} ``` ``` -------------------------------- ### tell() Source: https://python-soundfile.readthedocs.io Returns the current read/write position in the audio file. ```APIDOC ## tell() ### Description Returns the current read/write position in the audio file. ### Method tell ### Returns int - The current read/write position. ``` -------------------------------- ### soundfile.info Source: https://python-soundfile.readthedocs.io Returns an object with information about a SoundFile. Optionally prints additional information when verbose is True. ```APIDOC ## soundfile.info ### Description Returns an object with information about a SoundFile. ### Method Function call ### Endpoint soundfile.info(file, verbose=False) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** - Required - The file to get information about. - **verbose** (bool) - Optional - Whether to print additional information. ### Request Example None ### Response #### Success Response Returns an object with information about the SoundFile. #### Response Example None ``` -------------------------------- ### Run code coverage analysis Source: https://python-soundfile.readthedocs.io Execute tests with coverage tracking and generate an HTML report. ```bash coverage run --source soundfile -m pytest coverage html ``` -------------------------------- ### Write random data to a file using sf.write Source: https://python-soundfile.readthedocs.io Writes 10 frames of random audio data to a new WAV file with a specified sample rate and subtype. ```python >>> import numpy as np >>> import soundfile as sf >>> sf.write('stereo_file.wav', np.random.randn(10, 2), 44100, 'PCM_24') ``` -------------------------------- ### Retrieve available subtypes using sf.available_subtypes Source: https://python-soundfile.readthedocs.io Returns a dictionary of subtypes compatible with a specific format, such as FLAC. ```python >>> import soundfile as sf >>> sf.available_subtypes('FLAC') {'PCM_24': 'Signed 24 bit PCM', 'PCM_16': 'Signed 16 bit PCM', 'PCM_S8': 'Signed 8 bit PCM'} ``` -------------------------------- ### Read audio file in blocks using sf.blocks Source: https://python-soundfile.readthedocs.io Iterates over an audio file in blocks of 1024 frames. ```python >>> import soundfile as sf >>> for block in sf.blocks('stereo_file.wav', blocksize=1024): >>> pass # do something with 'block' ``` -------------------------------- ### SoundFile.format_info Source: https://python-soundfile.readthedocs.io Property that returns a description of the major format of the sound file. ```APIDOC ## SoundFile.format_info ### Description Returns a description of the major format of the sound file. ### Property format_info ### Returns - **format_info** (str) - A description of the major format. ``` -------------------------------- ### Open and Close an Existing File Source: https://python-soundfile.readthedocs.io Open an existing file for reading and manually close it after use. ```python >>> myfile = SoundFile('existing_file.wav') >>> # do something with myfile >>> myfile.close() ``` -------------------------------- ### soundfile.write() Source: https://python-soundfile.readthedocs.io Writes audio data to a sound file. If the file exists, it will be truncated and overwritten. ```APIDOC ## soundfile.write() ### Description Writes audio data to a sound file. If the file exists, it will be truncated and overwritten. ### Method Function call ### Signature soundfile.write(file, data, samplerate, subtype=None, endian=None, format=None, closefd=True, compression_level=None, bitrate_mode=None) ### Parameters - **file** - Required - The file to write to. - **data** - Required - The audio data to write. - **samplerate** - Required - The sample rate of the audio data. - **subtype** (optional) - The subtype of the audio data. - **endian** (optional) - The endianness of the audio data. - **format** (optional) - The format of the audio file. - **closefd** (optional) - Whether to close the file descriptor. - **compression_level** (optional) - The compression level. - **bitrate_mode** (optional) - The bitrate mode. ### Notes If file exists, it will be truncated and overwritten. ``` -------------------------------- ### copy_metadata() Source: https://python-soundfile.readthedocs.io Returns a dictionary containing all metadata present in the SoundFile. Possible keys include 'title', 'copyright', 'software', 'artist', 'comment', 'date', 'album', 'license', 'tracknumber', and 'genre'. ```APIDOC ## copy_metadata() ### Description Get all metadata present in this SoundFile. ### Method copy_metadata ### Parameters None ### Returns - **metadata** (dict[str, str]) - A dict with all metadata. Possible keys are: 'title', 'copyright', 'software', 'artist', 'comment', 'date', 'album', 'license', 'tracknumber' and 'genre'. ``` -------------------------------- ### Run tests with pytest Source: https://python-soundfile.readthedocs.io Execute the test suite using the pytest framework. ```bash python -m pytest ``` -------------------------------- ### Read audio data with sf.read Source: https://python-soundfile.readthedocs.io Reads a stereo sound file and returns the audio data as a NumPy array along with the sample rate. ```python >>> import soundfile as sf >>> data, samplerate = sf.read('stereo_file.wav') >>> data array([[ 0.71329652, 0.06294799], [-0.26450912, -0.38874483], ... [ 0.67398441, -0.11516333]]) >>> samplerate 44100 ``` -------------------------------- ### SoundFile.samplerate Source: https://python-soundfile.readthedocs.io Property that returns the sample rate of the sound file. ```APIDOC ## SoundFile.samplerate ### Description Returns the sample rate of the sound file. ### Property samplerate ### Returns - **samplerate** (int) - The sample rate of the sound file. ``` -------------------------------- ### SoundFile.format Source: https://python-soundfile.readthedocs.io Property that returns the major format of the sound file. ```APIDOC ## SoundFile.format ### Description Returns the major format of the sound file. ### Property format ### Returns - **format** (str) - The major format of the sound file. ``` -------------------------------- ### SoundFile.mode Source: https://python-soundfile.readthedocs.io Property that returns the open mode the sound file was opened with. ```APIDOC ## SoundFile.mode ### Description Returns the open mode the sound file was opened with. ### Property mode ### Returns - **mode** (str) - The open mode used to open the sound file. ``` -------------------------------- ### flush() Source: https://python-soundfile.readthedocs.io Writes buffered data to the file system. Data written with write() is not immediately written but buffered; calling flush() ensures all changes are written. ```APIDOC ## flush() ### Description Write unwritten data to the file system. Data written with `write()` is not immediately written to the file system but buffered in memory to be written at a later time. Calling `flush()` makes sure that all changes are actually written to the file system. This has no effect on files opened in read-only mode. ### Method flush ### Parameters None ### Returns None ``` -------------------------------- ### soundfile.check_format Source: https://python-soundfile.readthedocs.io Checks if the combination of format, subtype, and endian is valid. ```APIDOC ## soundfile.check_format ### Description Checks if the combination of format, subtype, and endian is valid. ### Method Function call ### Endpoint soundfile.check_format(format, subtype=None, endian=None) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **format** - Required - The format to check. - **subtype** - Optional - The subtype to check. - **endian** - Optional - The endian to check. ### Request Example ```python import soundfile as sf sf.check_format('WAV', 'PCM_24') sf.check_format('FLAC', 'VORBIS') ``` ### Response #### Success Response Returns True if the combination is valid, False otherwise. #### Response Example ```python True False ``` ``` -------------------------------- ### soundfile.write Source: https://python-soundfile.readthedocs.io Writes audio data to a file. The function accepts a file path or file-like object, audio data as an array, and a sample rate, with optional parameters for subtype, format, endian, and compression. ```APIDOC ## soundfile.write ### Description Writes audio data to a file. The data type of the data does not select the file's data type; audio data is converted to the given subtype. ### Method Function call ### Endpoint soundfile.write(file, data, samplerate, subtype=None, format=None, endian=None, closefd=True, compression_level=None, bitrate_mode=None) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **file** (str or int or file-like object) - Required - The file to write to. - **data** (array_like) - Required - The data to write. Usually two-dimensional (frames x channels), but one-dimensional data can be used for mono files. Only data types 'float64', 'float32', 'int32', and 'int16' are supported. - **samplerate** (int) - Required - The sample rate of the audio data. - **subtype** (str, optional) - Optional - See default_subtype() for the default value and available_subtypes() for all possible values. - **format** - Optional - See SoundFile. - **endian** - Optional - See SoundFile. - **closefd** - Optional - See SoundFile. - **compression_level** - Optional - See SoundFile. - **bitrate_mode** - Optional - See SoundFile. ### Request Example ```python import numpy as np import soundfile as sf sf.write('stereo_file.wav', np.random.randn(10, 2), 44100, 'PCM_24') ``` ### Response #### Success Response No return value. #### Response Example None ``` -------------------------------- ### SoundFile.subtype_info Source: https://python-soundfile.readthedocs.io Property that returns a description of the subtype of the sound file. ```APIDOC ## SoundFile.subtype_info ### Description Returns a description of the subtype of the sound file. ### Property subtype_info ### Returns - **subtype_info** (str) - A description of the subtype. ``` -------------------------------- ### write(data) Source: https://python-soundfile.readthedocs.io Writes audio data from a NumPy array to the file at the current read/write position. This advances the position and enlarges the file if necessary. Note that writing int values to a float file does not scale the values to [-1.0, 1.0). ```APIDOC ## write(data) ### Description Write audio data from a NumPy array to the file. Writes a number of frames at the read/write position to the file. This also advances the read/write position by the same number of frames and enlarges the file if necessary. Note that writing int values to a float file will not scale the values to [-1.0, 1.0). If you write the value np.array([42], dtype='int32'), to a subtype='FLOAT' file, the file will then contain np.array([42.], dtype='float32'). ### Parameters - **data** (array_like) - Required - The data to write. Usually two-dimensional (frames x channels), but one-dimensional data can be used for mono files. Only the data types 'float64', 'float32', 'int32' and 'int16' are supported. ### Examples ``` >>> import numpy as np >>> from soundfile import SoundFile >>> myfile = SoundFile('stereo_file.wav') ``` Write 10 frames of random data to a new file: ``` >>> with SoundFile('stereo_file.wav', 'w', 44100, 2, 'PCM_24') as f: >>> f.write(np.random.randn(10, 2)) ``` ### See Also - buffer_write - read ``` -------------------------------- ### Control bitrate mode and compression level Source: https://python-soundfile.readthedocs.io Adjust output file size and quality by setting bitrate_mode and compression_level during write operations. ```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) ``` -------------------------------- ### SoundFile.name Source: https://python-soundfile.readthedocs.io Property that returns the file name of the sound file. ```APIDOC ## SoundFile.name ### Description Returns the file name of the sound file. ### Property name ### Returns - **name** (str) - The file name of the sound file. ``` -------------------------------- ### blocks(blocksize=None, overlap=0, frames=-1, dtype='float64', always_2d=False, fill_value=None, out=None) Source: https://python-soundfile.readthedocs.io Returns a generator for block-wise reading of the file. Yields blocks of audio data of the specified size, with optional overlap and early stopping. ```APIDOC ## blocks(blocksize=None, overlap=0, frames=-1, dtype='float64', always_2d=False, fill_value=None, out=None) ### Description Return a generator for block-wise reading. By default, the generator yields blocks of the given blocksize (using a given overlap) until the end of the file is reached; frames can be used to stop earlier. ### Parameters - **blocksize** (int) - Required - The number of frames to read per block. Either this or out must be given. - **overlap** (int, optional) - The number of frames to rewind between each block. - **frames** (int, optional) - The number of frames to read. If frames < 0, the file is read until the end. - **dtype** ({'float64', 'float32', 'int32', 'int16'}, optional) - See read(). - **always_2d** - See read(). - **fill_value** (float, optional) - See read(). - **out** (numpy.ndarray or subclass, optional) - See read(). If out is specified, the data is written into the given array instead of creating a new array. In this case, the arguments dtype and always_2d are silently ignored! ### Yields - **numpy.ndarray or type(out)** - Blocks of audio data. If out was given, and the requested frames are not an integer multiple of the length of out, and no fill_value was given, the last block will be a smaller view into out. ### Examples ``` >>> from soundfile import SoundFile >>> with SoundFile('stereo_file.wav') as f: >>> for block in f.blocks(blocksize=1024): >>> pass # do something with 'block' ``` ``` -------------------------------- ### buffer_read(frames=-1, dtype=None) Source: https://python-soundfile.readthedocs.io Reads audio data from the file and returns it as a buffer object. Converts audio data to the specified data type. ```APIDOC ## buffer_read(frames=-1, dtype=None) ### Description Reads audio data from the file and returns it as a buffer object. Converts audio data to the specified data type. ### Method buffer_read ### Parameters #### frames (int, optional) - The number of frames to read. If frames < 0, the whole rest of the file is read. #### dtype ({'float64', 'float32', 'int32', 'int16'}) - Audio data will be converted to the given data type. ### Returns _buffer_ - A buffer containing the read data. ``` -------------------------------- ### seek(frames, whence=0) Source: https://python-soundfile.readthedocs.io Sets the read/write position in the audio file. Returns the new absolute position in frames. ```APIDOC ## seek(frames, whence=0) ### Description Sets the read/write position in the audio file. Returns the new absolute position in frames. ### Method seek ### Parameters #### frames (int) - Required - The frame index or offset to seek. #### whence ({SEEK_SET, SEEK_CUR, SEEK_END}, optional) - By default (whence=SEEK_SET), frames are counted from the beginning of the file. whence=SEEK_CUR seeks from the current position (positive and negative values are allowed for frames). whence=SEEK_END seeks from the end (use negative value for frames). ### Returns int - The new absolute read/write position in frames. ### Example ``` >>> from soundfile import SoundFile, SEEK_END >>> myfile = SoundFile('stereo_file.wav') >>> myfile.seek(0) 0 >>> myfile.seek(0, SEEK_END) 44100 # this is the file length ``` ``` -------------------------------- ### SoundFileError Source: https://python-soundfile.readthedocs.io Base class for all soundfile-specific errors. ```APIDOC ## SoundFileError ### Description Base class for all soundfile-specific errors. ### Type Exception ``` -------------------------------- ### Read RAW audio files Source: https://python-soundfile.readthedocs.io RAW files require manual specification of channels, samplerate, and subtype because they lack header information for auto-detection. ```python import soundfile as sf data, samplerate = sf.read('myfile.raw', channels=1, samplerate=44100, subtype='FLOAT') ``` -------------------------------- ### Skip file descriptor tests on Windows Source: https://python-soundfile.readthedocs.io Use this command to bypass tests that utilize file descriptors, which may fail on Windows due to compiler mismatches in libsndfile DLLs. ```bash python setup.py test --pytest-args="-knot\ fd" ``` -------------------------------- ### SoundFile.sections Source: https://python-soundfile.readthedocs.io Property that returns the number of sections of the sound file. ```APIDOC ## SoundFile.sections ### Description Returns the number of sections of the sound file. ### Property sections ### Returns - **sections** (int) - The number of sections. ``` -------------------------------- ### read(frames=-1, dtype='float64', always_2d=False, fill_value=None, out=None) Source: https://python-soundfile.readthedocs.io Reads audio data from the file and returns it as a NumPy array. Supports various data types and options for handling mono files and filling missing frames. ```APIDOC ## read(frames=-1, dtype='float64', always_2d=False, fill_value=None, out=None) ### Description Reads audio data from the file and returns it as a NumPy array. Supports various data types and options for handling mono files and filling missing frames. ### Method read ### Parameters #### frames (int, optional) - The number of frames to read. If frames < 0, the whole rest of the file is read. #### dtype ({'float64', 'float32', 'int32', 'int16'}, optional) - Data type of the returned array, by default 'float64'. Floating point audio data is typically in the range from -1.0 to 1.0. Integer data is in the range from -2**15 to 2**15-1 for 'int16' and from -2**31 to 2**31-1 for 'int32'. #### always_2d (bool, optional) - By default, reading a mono sound file will return a one-dimensional array. With always_2d=True, audio data is always returned as a two-dimensional array, even if the audio file has only one channel. #### fill_value (float, optional) - If more frames are requested than available in the file, the rest of the output is filled with fill_value. If fill_value is not specified, a smaller array is returned. #### out (numpy.ndarray or subclass, optional) - If out is specified, the data is written into the given array instead of creating a new array. In this case, the arguments dtype and always_2d are silently ignored! If frames is not given, it is obtained from the length of out. ### Returns **audiodata** (numpy.ndarray or type(out)) - A two-dimensional NumPy (frames x channels) array is returned. If the sound file has only one channel, a one-dimensional array is returned. Use always_2d=True to return a two-dimensional array anyway. If out was specified, it is returned. If out has more frames than available in the file (or if frames is smaller than the length of out) and no fill_value is given, then only a part of out is overwritten and a view containing all valid frames is returned. ### Example ``` >>> from soundfile import SoundFile >>> myfile = SoundFile('stereo_file.wav') >>> myfile.read(3) array([[ 0.71329652, 0.06294799], [-0.26450912, -0.38874483], [ 0.67398441, -0.11516333]]) >>> myfile.close() ``` ``` -------------------------------- ### Read audio from a URL Source: https://python-soundfile.readthedocs.io Read audio data directly from a URL by wrapping the response in an io.BytesIO object. ```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())) ``` -------------------------------- ### SoundFile.subtype Source: https://python-soundfile.readthedocs.io Property that returns the subtype of data in the sound file. ```APIDOC ## SoundFile.subtype ### Description Returns the subtype of data in the sound file. ### Property subtype ### Returns - **subtype** (str) - The subtype of data in the sound file. ```