o �J�h`�� @s�dZdZddlZddlZddlmZmZmZddl m Z ddl m ZzeZWn ey1eZYnwddd d d d d dddd� Zidd�dd�dd�dd�dd�dd�dd�d d!�d"d#�d$d%�d&d'�d(d)�d*d+�d,d-�d.d/�d0d1�d2d3�d4d5d6d7d8d9d:d;d<d=� �Zid>d�d?d�d@d �dAd �dBd �dCd �dDd �dEd�dFdG�dHdI�dJdK�dLdM�dNdO�dPdQ�dRdS�dTdU�dVdW�idXdY�dZd[�d\d]�d^d_�d`da�dbdc�ddde�dfdg�dhdi�djdk�dldm�dndo�dpdq�drds�dtdu�dvdw�dxdy��Zddzd{d|d}�Zidd?�dd?�dd?�dd?�dd?�dd?�d d?�d"d?�d$d?�d&dD�d(dD�d*d?�d,df�d.d?�d0d?�d2d?�d~d?�d?d?d?dFdhd?d?dxd��Zd�d�d�d�d��Zdddd��Zz�ejd�k�rSdd�lmZd�e�d�ZnSejd�k�r�dd�lmZdd�lmZe�dd�k�rpd�Zn6e�dd�k�r{d�Zn+e d��!e�e����ejd�k�r�dd�lmZe�d�v�r�d�Zn d�e�d�Zne d���ddl"Z"ej#�$e"j%�Z&ej#�'e&e�Z(e�)e(�Z*Wnue e+e,f�y3ze d��Z-e-du�r�e d���e�)e-�Z*WnSe �y0ejd�k�r�d�Z.nejd�k�r�d�Z.n ejd�k�rd�Z.n�dd�lmZejd�k�r)e�d�k�r)ej#�/d���rd�nd�Z0e�)ej#�'e0e.��Z*ne�)e.�Z*YnwYnwe�1e*�2���3d�d��Z4e4�5d���rMe4e6d��d�Z4 �  �d�d�d��Z7  d�d�d��Z8    �d�d�d��Z9Gd�d��d�e:�Z;d�d�d��Z<d�d��Z=d�d�d��Z>d�d�d��Z?d�d��Z@Gd�d��d�e:�ZAd�d�d��ZBd�d��ZCd�d��ZDd�d��ZEd�dÄZFd�dńZGe*jHfd�dDŽZId�dɄZJd�d˄ZKd�d̈́ZLGd�dτd�eM�ZNGd�dфd�eNeO�ZPGd�dӄd�eP�ZQdS)�akpython-soundfile is an audio library based on libsndfile, CFFI and NumPy. Sound files can be read or written directly using the functions `read()` and `write()`. To read a sound file in a block-wise fashion, use `blocks()`. Alternatively, sound files can be opened as `SoundFile` objects. For further information, see https://python-soundfile.readthedocs.io/. z0.13.1�N)�SEEK_SET�SEEK_CUR�SEEK_END)� find_library)�ffi��������� �) �title� copyright�software�artist�comment�dateZalbum�licenseZ tracknumberZgenre�WAViZAIFFi�AUi�RAWiZPAFiZSVXi�NISTiZVOCiZIRCAMi ZW64i ZMAT4i ZMAT5i ZPVFi�XIiZHTKiZSDSiZAVRiiiiiii i!i"i#) �WAVEX�SD2�FLAC�CAF�WVE�OGG�MPC2K�RF64�MP3�PCM_S8�PCM_16�PCM_24�PCM_32�PCM_U8�FLOAT�DOUBLE�ULAW�ALAW�� IMA_ADPCM��MS_ADPCM��GSM610� � VOX_ADPCM�!Z NMS_ADPCM_16�"Z NMS_ADPCM_24�#Z NMS_ADPCM_32�$�G721_32�0�G723_24�1�G723_40�2�DWVW_12�@�DWVW_16�A�DWVW_24�B�DWVW_N�C�DPCM_8�P�DPCM_16�Q�VORBIS�`�OPUS�d�ALAC_16�p�ALAC_20�q�ALAC_24�r�ALAC_32�sZ MPEG_LAYER_I�Z MPEG_LAYER_II��MPEG_LAYER_III�ii i0)�FILE�LITTLE�BIG�CPUr)rrr r!r"r#r$r%�double�float�int�short)�float64�float32�int32�int16)�CONSTANTZAVERAGE�VARIABLE�darwin)�machineZ libsndfile_z.dylib�win32)� architecture�64bitzlibsndfile_x64.dll�32bitzlibsndfile_x86.dllz%no packaged library for Windows {} {}�linux)�aarch64Z aarch64_beZarmv8b�armv8lzlibsndfile_arm64.soz.soz%no packaged library for this platformZsndfilez8sndfile library not found using ctypes.util.find_libraryzlibsndfile.dylibzlibsndfile.dllz libsndfile.so�arm64z/opt/homebrew/lib/z/usr/local/lib/�utf-8�replacez libsndfile-�����reFTc Cs`t|d|| | | | | ��}|�|||�}|�|||||�}Wd�n1s&wY||jfS)aProvide audio data from a sound file as NumPy array. By default, the whole file is read from the beginning, but the position to start reading can be specified with *start* and the number of frames to read can be specified with *frames*. Alternatively, a range can be specified with *start* and *stop*. If there is less data left in the file than requested, the rest of the frames are filled with *fill_value*. If no *fill_value* is specified, a smaller array is returned. Parameters ---------- file : str or int or file-like object 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'``. .. note:: Reading int values from a float file will *not* scale the data to [-1.0, 1.0). If the file contains ``np.array([42.6], dtype='float32')``, you will read ``np.array([43], dtype='int32')`` for ``dtype='int32'``. 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. Other Parameters ---------------- 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 be 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, channels, format, subtype, endian, closefd See `SoundFile`. Examples -------- >>> 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 �rN)� SoundFile� _prepare_read�read� samplerate)�file�frames�start�stop�dtype� always_2d� fill_value�outr|�channels�format�subtype�endian�closefd�f�data�r��GC:\pinokio\api\whisper-webui.git\app\env\lib\site-packages\soundfile.pyr{�s V�� r{c Csvddl} | �|�}|jdkrd} n|jd} t|d|| ||||||� �} | �|�Wd�dS1s4wYdS)aWrite data to a sound file. .. note:: If *file* exists, it will be truncated and overwritten! Parameters ---------- file : str or int or file-like object The file to write to. See `SoundFile` for details. data : array_like 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. .. note:: The data type of *data* does **not** select the data type of the written file. Audio data will be converted to the given *subtype*. 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')``. samplerate : int The sample rate of the audio data. subtype : str, optional See `default_subtype()` for the default value and `available_subtypes()` for all possible values. Other Parameters ---------------- format, endian, closefd, compression_level, bitrate_mode See `SoundFile`. Examples -------- Write 10 frames of random data to a new file: >>> import numpy as np >>> import soundfile as sf >>> sf.write('stereo_file.wav', np.random.randn(10, 2), 44100, 'PCM_24') rNr�w)�numpy�asarray�ndim�shapery�write) r}r�r|r�r�r�r��compression_level� bitrate_mode�npr�r�r�r�r�r�8s-    � "�r�c csn�t|d| | | || |��!}|�|||�}|�||||||| �D]}|VqWd�dS1s0wYdS)a8Return a generator for block-wise reading. 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. If you stop iterating over the generator before it's exhausted, the sound file is not closed. This is normally not a problem because the file is opened in read-only mode. To close the file properly, the generator's ``close()`` method can be called. Parameters ---------- file : str or int or file-like object The file to read from. See `SoundFile` for details. blocksize : int 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. 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*. Other Parameters ---------------- frames, start, stop See `read()`. dtype : {'float64', 'float32', 'int32', 'int16'}, optional See `read()`. always_2d, fill_value, out See `read()`. samplerate, channels, format, subtype, endian, closefd See `SoundFile`. Examples -------- >>> import soundfile as sf >>> for block in sf.blocks('stereo_file.wav', blocksize=1024): >>> pass # do something with 'block' rxN)ryrz�blocks)r}� blocksize�overlapr~rr�r�r�r�r�r|r�r�r�r�r�r��blockr�r�r�r�qs� 3� ��"�r�c@s,eZdZdZdd�Zedd��Zdd�ZdS) �_SoundFileInfozInformation about a SoundFilecCs�||_t|��>}|j|_|j|_|j|_|j|_t|j�|j|_|j|_|j |_ |j |_ |j |_ |j |_ |j |_ |j|_Wd�dS1sHwYdS�N)�verbosery�namer|r�r~rb�durationr�r�r�� format_info� subtype_info�sections� extra_info)�selfr}r�r�r�r�r��__init__�s  "�z_SoundFileInfo.__init__cCsvt|jd�\}}t|d�\}}|dkrd�|||�}|S|dkr(d�||�}|S|dkr4d�|j�}|Sd�|�}|S)Ni�<rz{0:.0g}:{1:02.0g}:{2:05.3f} hz{0:02.0g}:{1:05.3f} minz {0:d} samplesz {0:.3f} s)�divmodr�r�r~)r��hours�rest�minutes�secondsr�r�r�r�� _duration_str�s� �  �z_SoundFileInfo._duration_strcCsDd�gd��}|jr|d�gd��7}d�|j�d��}|�||�S)N� )z{0.name}zsamplerate: {0.samplerate} Hzzchannels: {0.channels}zduration: {0._duration_str}z$format: {0.format_info} [{0.format}]z'subtype: {0.subtype_info} [{0.subtype}])z endian: {0.endian}zsections: {0.sections}zframes: {0.frames}zextra_info: """z {1}"""z )�joinr�r��splitr�)r��infoZindented_extra_infor�r�r��__repr__�s�� z_SoundFileInfo.__repr__N)�__name__� __module__� __qualname__�__doc__r��propertyr�r�r�r�r�r�r��s   r�cCs t||�S)z�Returns an object with information about a `SoundFile`. Parameters ---------- verbose : bool Whether to print additional information. )r�)r}r�r�r�r�r��s r�cCstttjtj��S)a�Return a dictionary of available major formats. Examples -------- >>> 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)'} )�dict�_available_formats_helper�_sndZSFC_GET_FORMAT_MAJOR_COUNTZSFC_GET_FORMAT_MAJORr�r�r�r��available_formats�s�r�cs$ttjtj�}t�fdd�|D��S)adReturn a dictionary of available subtypes. Parameters ---------- format : str If given, only compatible subtypes are returned. Examples -------- >>> 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'} c3s.�|]\}}�dust�|�r||fVqdSr�)� check_format)�.0r�r��r�r�r�� <genexpr>s � ��z%available_subtypes.<locals>.<genexpr>)r�r�ZSFC_GET_FORMAT_SUBTYPE_COUNTZSFC_GET_FORMAT_SUBTYPEr�)r��subtypesr�r�r��available_subtypess�r�c Cs,z tt|||��WSttfyYdSw)z�Check if the combination of format/subtype/endian is valid. Examples -------- >>> import soundfile as sf >>> sf.check_format('WAV', 'PCM_24') True >>> sf.check_format('FLAC', 'VORBIS') False F)�bool� _format_int� ValueError� TypeError)r�r�r�r�r�r�r�s  �r�cCst|�t�|���S)z�Return the default subtype for a given format. Examples -------- >>> import soundfile as sf >>> sf.default_subtype('WAV') 'PCM_16' >>> sf.default_subtype('MAT5') 'DOUBLE' )� _check_format�_default_subtypes�get�upperr�r�r�r��default_subtype)s r�c@s6eZdZdZ   dedd�Zedd��Z ed d��Z ed d��Z ed d��Z ed d��Z ed d��Z edd��Z edd��Z edd��Z edd��Z edd��Z edd��Z edd��Z edd��Z edd��Z edd��ZdZdd�Zdd�Zdd�Zdd �Zd!d"�Zd#d$�Zd%d&�Zd'd(�Zd)d*�Zd+d,�Z e!fd-d.�Z"d/d0�Z# 3 dfd4d5�Z$dgd6d7�Z%d8d9�Z&d:d;�Z'd<d=�Z( 2 dhd?d@�Z)didAdB�Z*dCdD�Z+dEdF�Z,dGdH�Z-dIdJ�Z.dKdL�Z/dMdN�Z0dOdP�Z1dQdR�Z2dSdT�Z3dUdV�Z4dWdX�Z5dYdZ�Z6d[d\�Z7d]d^�Z8d_d`�Z9dadb�Z:dcdd�Z;dS)jryz�A sound file. For more documentation see the __init__() docstring (which is also used for the online documentation (https://python-soundfile.readthedocs.io/). rxNTc Cs�t|d�r |��n|}||_|durt|dd�}t|�} ||_| |_| |_t|||||||�|_ |� || |�|_ t |�� d�rH|��rH|�d�t�|j tjtjtj�|jdurl|�|j�|jdurn|�|j�dSdSdS)a�Open a sound file. If a file is opened with `mode` ``'r'`` (the default) or ``'r+'``, no sample rate, channels or file format need to be given because the information is obtained from the file. An exception is the ``'RAW'`` data format, which always requires these data points. File formats consist of three case-insensitive strings: * a *major format* which is by default obtained from the extension of the file name (if known) and which can be forced with the format argument (e.g. ``format='WAVEX'``). * a *subtype*, e.g. ``'PCM_24'``. Most major formats have a default subtype which is used if no subtype is specified. * an *endian-ness*, which doesn't have to be specified at all in most cases. A `SoundFile` object is a *context manager*, which means if used in a "with" statement, `close()` is automatically called when reaching the end of the code block inside the "with" statement. Parameters ---------- file : str or int or file-like object The file to open. This can be a file name, a file descriptor or a Python file object (or a similar object with the methods ``read()``/``readinto()``, ``write()``, ``seek()`` and ``tell()``). mode : {'r', 'r+', 'w', 'w+', 'x', 'x+'}, optional Open mode. Has to begin with one of these three characters: ``'r'`` for reading, ``'w'`` for writing (truncates *file*) or ``'x'`` for writing (raises an error if *file* already exists). Additionally, it may contain ``'+'`` to open *file* for both reading and writing. The character ``'b'`` for *binary mode* is implied because all sound files have to be opened in this mode. If *file* is a file descriptor or a file-like object, ``'w'`` doesn't truncate and ``'x'`` doesn't raise an error. samplerate : int The sample rate of the file. If `mode` contains ``'r'``, this is obtained from the file (except for ``'RAW'`` files). channels : int The number of channels of the file. If `mode` contains ``'r'``, this is obtained from the file (except for ``'RAW'`` files). subtype : str, sometimes optional The subtype of the sound file. If `mode` contains ``'r'``, this is obtained from the file (except for ``'RAW'`` files), if not, the default value depends on the selected `format` (see `default_subtype()`). See `available_subtypes()` for all possible subtypes for a given `format`. endian : {'FILE', 'LITTLE', 'BIG', 'CPU'}, sometimes optional The endian-ness of the sound file. If `mode` contains ``'r'``, this is obtained from the file (except for ``'RAW'`` files), if not, the default value is ``'FILE'``, which is correct in most cases. format : str, sometimes optional The major format of the sound file. If `mode` contains ``'r'``, this is obtained from the file (except for ``'RAW'`` files), if not, the default value is determined from the file extension. See `available_formats()` for all possible values. closefd : bool, optional Whether to close the file descriptor on `close()`. Only applicable if the *file* argument is a file descriptor. compression_level : float, optional The compression level on 'write()'. The compression level should be between 0.0 (minimum compression level) and 1.0 (highest compression level). See `libsndfile document <https://github.com/libsndfile/libsndfile/blob/c81375f070f3c6764969a738eacded64f53a076e/docs/command.md>`__. bitrate_mode : {'CONSTANT', 'AVERAGE', 'VARIABLE'}, optional The bitrate mode on 'write()'. See `libsndfile document <https://github.com/libsndfile/libsndfile/blob/c81375f070f3c6764969a738eacded64f53a076e/docs/command.md>`__. Examples -------- >>> from soundfile import SoundFile Open an existing file for reading: >>> myfile = SoundFile('existing_file.wav') >>> # do something with myfile >>> myfile.close() Create a new sound file for reading and writing using a with statement: >>> 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 � __fspath__N�modezr+r)�hasattrr��_name�getattr� _check_mode�_mode�_compression_level� _bitrate_mode�_create_info_struct�_info�_open�_file�set� issuperset�seekable�seekr�� sf_commandZSFC_SET_CLIPPING�_ffi�NULL�SF_TRUE�_set_compression_level�_set_bitrate_mode) r�r}r�r|r�r�r�r�r�r�r��mode_intr�r�r�r�As.g  � �   �zSoundFile.__init__cC�|jSr�)r��r�r�r�r��<lambda>��zSoundFile.<lambda>cCr�r�)r�r�r�r�r�r��r�cC�|jjSr�)r�r|r�r�r�r�r���cCr�r��r�r~r�r�r�r�r��r�cCr�r�)r�r�r�r�r�r�r��r�cC�t|jjtj@�Sr�)� _format_strr�r�r��SF_FORMAT_TYPEMASKr�r�r�r�r���cCr�r�)r�r�r�r��SF_FORMAT_SUBMASKr�r�r�r�r��r�cCr�r�)r�r�r�r�ZSF_FORMAT_ENDMASKr�r�r�r�r��r�cC�t|jjtj@�dS�Nr)� _format_infor�r�r�r�r�r�r�r�r��� ��cCr�r�)r�r�r�r�r�r�r�r�r�r��r�cCr�r�)r�r�r�r�r�r�r��r�cCs |jduSr�)r�r�r�r�r�r��s cCs t�|j�Sr�)r��sf_errorr�r�r�r�r�r��s cCr�r�)r�r�r�r�r�r��r�cCr�r�)r�r�r�r�r�r��r�cCs8t�dd�}t�|jtj|t�|��t�|��dd�S)z8Retrieve the log string generated when opening the file.zchar[]i@rurv) r��newr�r�r�ZSFC_GET_LOG_INFO�sizeof�string�decode)r�r�r�r�r�r��s   �zSoundFile.extra_infocCsD|jdur d�|j�nd}||jdurd�|j�nd7}d�||�S)Nz, compression_level={0}�z, bitrate_mode='{0}'z�SoundFile({0.name!r}, mode={0.mode!r}, samplerate={0.samplerate}, channels={0.channels}, format={0.format!r}, subtype={0.subtype!r}, endian={0.endian!r}{1}))r�r�r�)r�Zcompression_settingr�r�r�r��s  ��  ���zSoundFile.__repr__cC� |��dSr���closer�r�r�r��__del__�� zSoundFile.__del__cCs|Sr�r�r�r�r�r�� __enter__�szSoundFile.__enter__cGr�r�r�)r��argsr�r�r��__exit__r�zSoundFile.__exit__cCsF|tvr|��t�|jt||���}t|�dSt�|||�dS)z:Write text meta-data in the sound file through properties.N) � _str_types�_check_if_closedr�Z sf_set_stringr��encode� _error_check�object� __setattr__)r�r��value�errr�r�r�rs� zSoundFile.__setattr__cCsJ|tvr|��t�|jt|�}|rt�|��dd�SdStd� |���)z9Read text meta-data in the sound file through properties.rurvr�z)'SoundFile' object has no attribute {0!r}) rrr�� sf_get_stringr�r�r�r��AttributeErrorr�)r�r�r�r�r�r�� __getattr__s�zSoundFile.__getattr__cCr�r�r�r�r�r�r��__len__�zSoundFile.__len__cCsdS)NTr�r�r�r�r��__bool__szSoundFile.__bool__cCs|��Sr�)r r�r�r�r�� __nonzero__"r zSoundFile.__nonzero__cCs|jjtjkS)z)Return True if the file supports seeking.)r�r�r�r�r�r�r�r�r�'szSoundFile.seekablecCs&|��t�|j||�}t|j�|S)a�Set the read/write position. Parameters ---------- frames : int 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. Examples -------- >>> from soundfile import SoundFile, SEEK_END >>> myfile = SoundFile('stereo_file.wav') Seek to the beginning of the file: >>> myfile.seek(0) 0 Seek to the end of the file: >>> myfile.seek(0, SEEK_END) 44100 # this is the file length )rr�Zsf_seekr�r� _errorcode)r�r~�whence�positionr�r�r�r�+s$ zSoundFile.seekcCs |�dt�S)z'Return the current read/write position.r)r�rr�r�r�r��tellTs zSoundFile.tellrwreFcCs�|dur|�||�}|�|||�}n|dks|t|�kr t|�}|�d||�}t|�|kr?|dur9|d|�}|S|||d�<|S)a Read from the file and return data as NumPy array. Reads the given number of frames in the given data format starting at the current read/write position. This advances the read/write position by the same number of frames. By default, all frames from the current read/write position to the end of the file are returned. Use `seek()` to move the current read/write position. 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'``. .. note:: Reading int values from a float file will *not* scale the data to [-1.0, 1.0). If the file contains ``np.array([42.6], dtype='float32')``, you will read ``np.array([43], dtype='int32')`` for ``dtype='int32'``. 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. Other Parameters ---------------- 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 be 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*. Examples -------- >>> from soundfile import SoundFile >>> myfile = SoundFile('stereo_file.wav') Reading 3 frames from a stereo file: >>> myfile.read(3) array([[ 0.71329652, 0.06294799], [-0.26450912, -0.38874483], [ 0.67398441, -0.11516333]]) >>> myfile.close() See Also -------- buffer_read, .write Nrr{)� _check_frames�_create_empty_array�len� _array_io)r�r~r�r�r�r�r�r�r�r{XsP    �zSoundFile.readcCsT|j|dd�}|�|�}t�|d||j�}|�d|||�}||ks%J�t�|�S)a�Read from the file and return data as buffer object. Reads the given number of *frames* in the given data format starting at the current read/write position. This advances the read/write position by the same number of frames. By default, all frames from the current read/write position to the end of the file are returned. Use `seek()` to move the current read/write position. 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. See Also -------- buffer_read_into, .read, buffer_write N)r�z[]r{)r� _check_dtyper�r�r�� _cdata_io�buffer)r�r~r��ctype�cdataZ read_framesr�r�r�� buffer_read�s    zSoundFile.buffer_readcCs.|�|�}|�||�\}}|�d|||�}|S)a�Read from the file into a given buffer object. Fills the given *buffer* with frames in the given data format starting at the current read/write position (which can be changed with `seek()`) until the buffer is full or the end of the file is reached. This advances the read/write position by the number of frames that were read. Parameters ---------- buffer : writable buffer Audio frames from the file are written to this buffer. dtype : {'float64', 'float32', 'int32', 'int16'} The data type of *buffer*. Returns ------- int The number of frames that were read from the file. This can be less than the size of *buffer*. The rest of the buffer is not filled with meaningful data. See Also -------- buffer_read, .read r{)r� _check_bufferr)r�rr�rrr~r�r�r��buffer_read_into�s zSoundFile.buffer_read_intocCsBddl}|�|�}|�d|t|��}|t|�ksJ�|�|�dS)a�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 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. .. note:: The data type of *data* does **not** select the data type of the written file. Audio data will be converted to the given *subtype*. 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')``. 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 rNr�)r��ascontiguousarrayrr�_update_frames)r�r�r��writtenr�r�r�r��s . zSoundFile.writecCsD|�|�}|�||�\}}|�d|||�}||ksJ�|�|�dS)a�Write audio data from a buffer/bytes object to the file. Writes the contents of *data* to the file at the current read/write position. This also advances the read/write position by the number of frames that were written and enlarges the file if necessary. Parameters ---------- data : buffer or bytes A buffer or bytes object containing the audio data to be written. dtype : {'float64', 'float32', 'int32', 'int16'} The data type of the audio data stored in *data*. See Also -------- .write, buffer_read r�N)rrrr )r�r�r�rrr~r!r�r�r�� buffer_write0s  zSoundFile.buffer_writerc cst�ddl}d|jvrd|jvrtd��|�||�}|dur:|dur%td��|dur+|nt||�} |�| ||�}d} n|durBtd��t|�}d } d} |dkr�| durUd} n t| �} | |d| �<t|| |�} |�| ||||| d��|r�| dur�|� || d��} n || d�| dd�<|||kr�|dur�|d||�}n|}| r�|� |�n|V|| 8}|dksNdSdS) a�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 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()`. 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*. Other Parameters ---------------- always_2d, fill_value, out See `read()`. fill_value : float, optional See `read()`. 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! Examples -------- >>> from soundfile import SoundFile >>> with SoundFile('stereo_file.wav') as f: >>> for block in f.blocks(blocksize=1024): >>> pass # do something with 'block' rNrx�+z*blocks() is not allowed in write-only modez)One of {blocksize, out} must be specifiedTz-Only one of {blocksize, out} may be specifiedF) r�r��SoundFileRuntimeErrorrr��minrrr{�copy)r�r�r�r~r�r�r�r�r��out_sizeZcopy_outZoverlap_memoryZ output_offsetZtoreadr�r�r�r�r�KsF�2 � �zSoundFile.blockscCsX|dur|��}t�|jtjt�d|�t�d��}|r&t�|j�}t |d��||j _ dS)anTruncate the file to a given number of frames. After this command, the read/write position will be at the new end of the file. Parameters ---------- frames : int, optional Only the data before *frames* is kept, the rest is deleted. If not specified, the current read/write position is used. Nz sf_count_t*Z sf_count_tzError truncating the file) rr�r�r�ZSFC_FILE_TRUNCATEr�r�r�r��LibsndfileErrorr�r~)r�r~rr�r�r��truncate�s   �   zSoundFile.truncatecCs|��t�|j�dS)ajWrite 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. N)rr�Z sf_write_syncr�r�r�r�r��flush�s zSoundFile.flushcCs0|js|��t�|j�}d|_t|�dSdS)z.Close the file. Can be called multiple times.N)�closedr*r�Zsf_closer�r)r�rr�r�r�r��s   �zSoundFile.closecCs0t|ttf�rOtj�|�r/d|jvrtd�|j ���t |j�� d�r/t� t� |tjtjB��tj}t|t�rGtjdkr@tj}n|�t���}||||j�}n*t|t�r^t�|||j|�}nt||�rqt�|�|�||jtj�}ntd�|j ���|tjkr�t� |�}t!|d�|j �d��|tj"kr�d|j_#|S) z9Call the appropriate sf_open*() function from libsndfile.�xzFile exists: {0!r}zw+rmzInvalid file: {0!r}zError opening {0!r}: ��prefixr)$� isinstance�_unicode�bytes�_os�path�isfiler��OSErrorr�r�r�r�r��open�O_WRONLY�O_TRUNCr�Zsf_open�_sys�platformZ sf_wchar_openr�getfilesystemencodingr�rcZ sf_open_fd�_has_virtual_io_attrsZsf_open_virtual�_init_virtual_ior�r�r�r�r(� SFM_WRITEr~)r�r}r�r�Z openfunctionZfile_ptrrr�r�r�r��s2        �   zSoundFile._opencs�t�d��fdd��}t�d��fdd��}t�d��fdd ��}t�d ��fd d ��}t�d ��fdd��}|||||d�|_t�d|j�S)z4Initialize callback functions for sf_open_virtual().Zsf_vio_get_filelencs,���}��dt����}��|t�|S�Nr)rr�rr)� user_data�curr�size�r}r�r��vio_get_filelen�s   z3SoundFile._init_virtual_io.<locals>.vio_get_filelenZ sf_vio_seekcs��||����Sr�)r�r)�offsetrr@rCr�r��vio_seeks z,SoundFile._init_virtual_io.<locals>.vio_seekZ sf_vio_readcs\zt�||�}��|�}W|Sty-��|�}t|�}t�||�}||d|�<Y|Swr?)r�r�readintor r{r)�ptr�countr@�bufZ data_readr�rCr�r��vio_read s   �  �z,SoundFile._init_virtual_io.<locals>.vio_readZ sf_vio_writecs2t�||�}|dd�}��|�}|dur|}|Sr�)r�rr�)rHrIr@rJr�r!rCr�r�� vio_writes   z-SoundFile._init_virtual_io.<locals>.vio_writeZ sf_vio_tellcs���Sr�)r)r@rCr�r��vio_tell!sz,SoundFile._init_virtual_io.<locals>.vio_tell)Z get_filelenr�r{r�rzSF_VIRTUAL_IO*)r��callbackZ _virtual_ior�)r�r}rDrFrKrLrMr�rCr�r=�s"  �zSoundFile._init_virtual_iocCstS)z�Return all attributes used in __setattr__ and __getattr__. This is useful for auto-completion (e.g. IPython). )rr�r�r�r��_getAttributeNames.szSoundFile._getAttributeNamescCs|jrtd��dS)z�Check if the file is closed and raise an error if it is. This should be used in every method that uses self._file. zI/O operation on closed fileN)r+r$r�r�r�r�r6s�zSoundFile._check_if_closedcCsJ|��r|j|��}|dks||kr|dur|}|S|dkr#td��|S)z8Reduce frames to no more than are available in the file.rNz/frames must be specified for non-seekable files)r�r~rr�)r�r~r�Zremaining_framesr�r�r�r?s�zSoundFile._check_framescCsV|t��vsJ�t|t�st�|�}tt|�|jt� |��\}}|r't d��||fS)z1Convert buffer to cdata and check for valid size.z*Data size must be a multiple of frame size) � _ffi_types�valuesr/r1r�� from_bufferr�rr�r�r�)r�r�rr~� remainderr�r�r�rJs  �zSoundFile._check_buffercCs8ddl}|s |jdkr||jf}n|f}|j||dd�S)z-Create an empty array with appropriate shape.rNr�C)�order)r�r��empty)r�r~r�r�r�r�r�r�r�rUs  zSoundFile._create_empty_arrayc Cs2zt|WStytd�tt���|���w)z7Check if dtype string is valid and return ctype string.z(dtype must be one of {0!r} and not {1!r})rP�KeyErrorr�r��sorted�keys)r�r�r�r�r�r^s   ��zSoundFile._check_dtypecCs�|jdvrtd�|j|jdkrd���d���|jdkrdn|jd}||jkr3td�|j|j|���|jjs;td��|�|jj �}|jj t � |�ksMJ�t � |d|jd d �}|�||||�S) z+Check array and call low-level IO function.)rrzInvalid shape: {0!r} ({1})rz0 dimensions not supportedztoo many dimensionsz5Invalid shape: {0!r} (Expected {1} channels, got {2})zData must be C-contiguous�*r�r)r�r�r�r�r��flags� c_contiguousrr�r��itemsizer�r��cast�__array_interface__r)r��action�arrayr~Zarray_channelsrrr�r�r�rfs $ zSoundFile._array_iocCsr|t��vsJ�|��|��r|��}ttd|d|�}||j||�}t|j �|��r7|� ||t �|S)z.Call one of libsndfile's read/write functions.Zsf_�f_) rPrQrr�rr�r�r�rrr�r)r�r`r�rr~rA�funcr�r�r�rts zSoundFile._cdata_iocCsD|��r|��}|�dt�|j_|�|t�dS|jj|7_dS)z!Update self.frames after writing.rN)r�rr�rr�r~r)r�r!rAr�r�r�r �s zSoundFile._update_framescCs||dkr |��s td��|dkr|durtd��t||��|j�\}}}||kr*|}|dkr2||}|��r<|�|t�|S)z)Seek to start frame and calculate length.rz(start is only allowed for seekable filesNz&Only one of {frames, stop} may be used)r�r�r��slice�indicesr~r�r)r�rr�r~�_r�r�r�rz�s zSoundFile._prepare_readcCsBi}t��D]\}}t�|j|�}|rt�|��dd�||<q|S)a5Get all metadata present in this SoundFile Returns ------- metadata: dict[str, str] A dict with all metadata. Possible keys are: 'title', 'copyright', 'software', 'artist', 'comment', 'date', 'album', 'license', 'tracknumber' and 'genre'. rurv)r�itemsr�rr�r�r�r�)r��strsZstrtypeZstridr�r�r�r�� copy_metadata�s �zSoundFile.copy_metadatacCsf|tvsJ�t�d�}t||d<t�|jtj|t�|��}|tjkr1t� |j�}t |d|����dS)z,Call libsndfile's set bitrate mode function.zint[1]rzError set bitrate mode N) �_bitrate_modesr�r�r�r�r�ZSFC_SET_BITRATE_MODEr�r�r�r()r�r�Zpointer_bitrate_moderr�r�r�r��s     �zSoundFile._set_bitrate_modecCszd|kr dkstd��td��t�d�}||d<t�|jtj|t�|��}|tjkr;t� |j�}t |d|����dS)z1Call libsndfile's set compression level function.rrz)Compression level must be in range [0..1]z double[1]zError set compression level N) r�r�r�r�r�r�ZSFC_SET_COMPRESSION_LEVELr�r�r�r()r�r�Zpointer_compression_levelrr�r�r�r��s�   �z SoundFile._set_compression_level) rxNNNNNTNN)rwreFNN)rwN)NrrwreFNNr�)<r�r�r�r�r�r�r�r�r|r~r�r�r�r�r�r�r�r+rr�r�r�r�r�r�r�r�rr r r rr�rr�rr{rrr�r"r�r)r*r�r�r=rOrrrrrrrr rzrir�r�r�r�r�r�ry9s� �     �����          ) � ^#!6 � ] $3       ryr�cCs|dkr t||d��dS)z+Raise LibsndfileError if there is an error.rr-N)r()rr.r�r�r�r�s �rcCs t|�}|durt|�}|durtd�|���nt|ttf�s&td�|���z |t|��O}Wnt y>t d�|���w|durFd}nt|ttf�sTtd�|���z |t |��O}Wnt ylt d�|���wt � d�}||_d |_t�|�tjkr�t d ��|S) z8Return numeric ID for given format|subtype|endian combo.Nz)No default subtype for major format {0!r}zInvalid subtype: {0!r}zUnknown subtype: {0!r}r]zInvalid endian-ness: {0!r}zUnknown endian-ness: {0!r}�SF_INFO*rz1Invalid combination of format, subtype and endian)r�r�r�r�r/r0�str� _subtypesr�rWr��_endiansr�r�r�r�Zsf_format_checkZSF_FALSE)r�r�r��resultr�r�r�r�r��s@�� � � �r�cCs�t|ttf�std�|���t|�}|�d�st|�t|�kr&td�|���t|� d��dkr3td��d|vr<t j }|Sd|vrEt j }|St j }|S)z=Check if mode is valid and return its integer representation.zInvalid mode: {0!r}zxrwb+Zxrwrz&mode must contain exactly one of 'xrw'r#rx)r/r0rlr�r�r�� differencerr�� intersectionr�ZSFM_RDWR�SFM_READr>)r�Zmode_setr�r�r�r�r��s��r�c Cs�|}|durt||�}t|ttf�sJ�nt|�t�d�}d|vs(|��dkrG|dur0td��||_ |dur;td��||_ t |||�|_ |St dd�|||||fD��rYtd ��|S) z*Check arguments and create SF_INFO struct.Nrkrxrzsamplerate must be specifiedzchannels must be specifiedcss�|]}|duVqdSr�r�)r��argr�r�r�r�s�z&_create_info_struct.<locals>.<genexpr>z\Not allowed for existing files (except 'RAW'): samplerate, channels, format, subtype, endian)�_get_format_from_filenamer/r0rlr�r�r�r�r�r|r�r�r��any) r}r�r|r�r�r�r�Zoriginal_formatr�r�r�r�r��s(  �  �r�cCsrd}t|d|�}ztj�|�ddd�}|�dd�}Wn ty%Ynw|��tvr7d|vr7td � |���|S) aReturn a format string obtained from file (or file.name). If file already exists (= read mode), an empty string is returned on error. If not, an exception is raised. The return type will always be str or unicode (even if file/file.name is a bytes object). r�r�rwrNrurvrxzGNo format specified and unable to get format from file extension: {0!r}) r�r2r3�splitextr�� Exceptionr��_formatsr�r�)r}r�r�r�r�r�rts  ��rtcCs:tttfD]}|��D]\}}||kr|Sq qdS)z;Return the string representation of a given numeric format.zn/a)rxrmrnrg)� format_int� dictionary�k�vr�r�r�r�1s ��r�cCsTt�d�}||_t�tj||t�d��|j}t|j�|r't� |�� dd�fSdfS)z6Return the ID and short description of a given format.zSF_FORMAT_INFO*ZSF_FORMAT_INFOrurvr�) r�r�r�r�r�r�r�r�r�r�r�)ry� format_flagr�r�r�r�r�r�;s  ���r�ccsF�t�d�}t�tj||t�d��t|d�D]}t||�VqdS)z8Helper for available_formats() and available_subtypes().zint*rcrN)r�r�r�r�r�r��ranger�)Z count_flagr}rIryr�r�r�r�Fs � �r�cCsLt|ttf�std�|���z t|��}W|Sty%td�|���w)z4Check if `format_str` is valid and return format ID.zInvalid format: {0!r}zUnknown format: {0!r}) r/r0rlr�r�rxr�rWr�)Z format_strryr�r�r�r�Ns ��r�cCsN|tjk}|tjk}tt|d�t|d�t|d�p|t|d�p$t|d�p$|g�S)z>Check if file has all the necessary attributes for virtual IO.r�rr�r{rG)r�rrr>�allr�)r}r��readonlyZ writeonlyr�r�r�r<Ys   �r<c@�eZdZdZdS)�SoundFileErrorz-Base class for all soundfile-specific errors.N�r�r�r�r�r�r�r�r�r�esr�c@r�)r$zKsoundfile module runtime error. Errors that used to be `RuntimeError`.Nr�r�r�r�r�r$isr$c@s.eZdZdZd dd�Zedd��Zdd�Zd S) r(zjlibsndfile errors. Attributes ---------- code libsndfile internal error number. r�cCst�|||�||_||_dSr�)r$r��coder.)r�r�r.r�r�r�r�xs zLibsndfileError.__init__cCs(|jrt�|j�}t�|��dd�SdS)zRaw libsndfile error message.rurvz'(Garbled error message from libsndfile))r�r�Zsf_error_numberr�r�r�)r��err_strr�r�r�� error_string}s zLibsndfileError.error_stringcCs |j|jSr�)r.r�r�r�r�r��__str__�r�zLibsndfileError.__str__N�r�)r�r�r�r�r�r�r�r�r�r�r�r�r(os    r() rwrNreFNNNNNNNT)NNNTNN)NrrwrNreFNNNNNNNT)Fr�)NNr�)Rr�� __version__�osr2�sysr9rrrZ ctypes.utilrZ _find_libraryZ _soundfilerr��unicoder0� NameErrorrlrrxrmrnr�rPrjr:rl�_machineZ_packaged_libnamernZ _architecturer5r�Z_soundfile_datar3�dirname�__file__�_pathr�Z _full_pathZdlopenr�� ImportErrorr�Z_libnameZ_explicit_libname�isdirZ _hbrew_pathr�Zsf_version_stringr�Z__libsndfile_version__� startswithrr{r�r�rr�r�r�r�r�r�ryrr�r�r�rtr�ZSFC_GET_FORMAT_INFOr�r�r�r<rwr�� RuntimeErrorr$r(r�r�r�r��<module>s<    �� �������� � � � � �������������� � � � � ������������������� �!�"�&�������� � � � � ���������      �        � ����  �] �9 �; 4        
Memory