3

6^O8                 @   s   d Z ddlmZmZmZ ddlZddlZddlZddlZdddgZ	G dd de
ZdZd	Zd
ZeefZdd ZdddZdd Zdd ZdddZdd Zejd d	krdd Zndd ZdS )z
Module to read / write wav files using numpy arrays

Functions
---------
`read`: Return the sample rate (in samples/sec) and data from a WAV file.

`write`: Write a numpy array as a WAV file.

    )divisionprint_functionabsolute_importNWavFileWarningreadwritec               @   s   e Zd ZdS )r   N)__name__
__module____qualname__ r   r   1/tmp/pip-build-vw4w4j08/scipy/scipy/io/wavfile.pyr      s         i  c             C   sF  |r
d}nd}t j|d | jdd  }}d}|dk r@tdt j|d | jd}|d7 }|\}}}}	}
}|tko||dkr
t j|d
 | jd	d }|d	7 }|dkr| jd}|d7 }|dd }|rd}nd}|j|r
t j|d |dd d }ntd|tkrtd||kr4| j||  |||||	|
|fS )a  
    Returns
    -------
    size : int
        size of format subchunk in bytes (minus 8 for "fmt " and itself)
    format_tag : int
        PCM, float, or compressed format
    channels : int
        number of channels
    fs : int
        sampling frequency in samples per second
    bytes_per_second : int
        overall byte rate for the file
    block_align : int
        bytes per sample, including all channels
    bit_depth : int
        bits per sample
    ><I   r      z.Binary structure of wave file is not compliantZHHIIHH   H   s         8qs         8qNzUnknown wave file format      r   r   )structunpackr   
ValueErrorWAVE_FORMAT_EXTENSIBLEendswithKNOWN_WAVE_FORMATS)fidis_big_endianfmtsizeres
bytes_read
format_tagchannelsfsbytes_per_secondblock_align	bit_depthZext_chunk_sizeZextensible_chunk_dataZraw_guidtailr   r   r   _read_fmt_chunk'   s:    



r,   Fc             C   s   |r
d}nd}t j|| jdd }|d }|dkr:d}	n0|rDd}	nd}	|tkr^|	d	| 7 }	n|	d
| 7 }	|stj| j||	d}
n0| j }tj| |	d||| fd}
| j||  |dkr|
j	d|}
|
S )Nz>Iz<Ir   r      u1r   r   zi%dzf%d)dtypec)r/   modeoffsetshaper   )
r   r   r   WAVE_FORMAT_PCMnumpyZ
frombuffertellZmemmapseekZreshape)r   r%   r&   r*   r    mmapr!   r"   Zbytes_per_sampler/   datastartr   r   r   _read_data_chunki   s,    r<   c             C   s<   |r
d}nd}| j d}|r8tj||d }| j|d d S )Nz>Iz<Ir   r   r   )r   r   r   r8   )r   r    r!   r:   r"   r   r   r   _skip_unknown_chunk   s    
r=   c             C   s|   | j d}|dkrd}d}n$|dkr.d}d}ntdjt|tj|| j dd	 d
 }| j d}|dkrttd||fS )Nr   s   RIFFFz<Is   RIFXTz>Iz!File format {}... not understood.r   r-   s   WAVEzNot a WAV file.)r   r   formatreprr   r   )r   Zstr1r    r!   	file_sizeZstr2r   r   r   _read_riff_chunk   s    

rA   c             C   s  t | dr| }d}n
t| d}z^t|\}}d}d}d}d}t}	x6|j |k rz|jd}
|
s|rtjdj|j |t	dd	 P qt
d
nt|
dk rt
d|
dkrd}t||}|dd \}	}}|d }|dkrt
dj|qF|
dkrt|| qF|
dkr2d}|st
dt||	||||}qF|
dkrHt|| qF|
dkr^t|| qFtjdt	dd	 t|| qFW W dt | ds|j  n
|jd X ||fS ) a	  
    Open a WAV file

    Return the sample rate (in samples/sec) and data from a WAV file.

    Parameters
    ----------
    filename : string or open file handle
        Input wav file.
    mmap : bool, optional
        Whether to read data as memory-mapped.
        Only to be used on real files (Default: False).

        .. versionadded:: 0.12.0

    Returns
    -------
    rate : int
        Sample rate of wav file.
    data : numpy array
        Data read from wav file.  Data-type is determined from the file;
        see Notes.

    Notes
    -----
    This function cannot read wav files with 24-bit data.

    Common data types: [1]_

    =====================  ===========  ===========  =============
         WAV format            Min          Max       NumPy dtype
    =====================  ===========  ===========  =============
    32-bit floating-point  -1.0         +1.0         float32
    32-bit PCM             -2147483648  +2147483647  int32
    16-bit PCM             -32768       +32767       int16
    8-bit PCM              0            255          uint8
    =====================  ===========  ===========  =============

    Note that 8-bit PCM is unsigned.

    References
    ----------
    .. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming
       Interface and Data Specifications 1.0", section "Data Format of the
       Samples", August 1991
       http://www.tactilemedia.com/info/MCI_Control_Info.html

    Examples
    --------
    >>> from os.path import dirname, join as pjoin
    >>> import scipy.io as sio

    Get the filename for an example .wav file from the tests/data directory.

    >>> data_dir = pjoin(dirname(sio.__file__), 'tests', 'data')
    >>> wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav')

    Load the .wav file contents.

    >>> samplerate, data = sio.wavfile.read(wav_fname)
    >>> print(f"number of channels = {data.shape[1]}")
    number of channels = 2
    >>> length = data.shape[0] / samplerate
    >>> print(f"length = {length}s")
    length = 0.01s

    Plot the waveform.

    >>> import matplotlib.pyplot as plt
    >>> import numpy as np
    >>> time = np.linspace(0., length, data.shape[0])
    >>> plt.plot(time, data[:, 0], label="Left channel")
    >>> plt.plot(time, data[:, 1], label="Right channel")
    >>> plt.legend()
    >>> plt.xlabel("Time [s]")
    >>> plt.ylabel("Amplitude")
    >>> plt.show()

    r   Frbr   r-   r   zQReached EOF prematurely; finished at {:d} bytes, expected {:d} bytes from header.r   )
stacklevelzUnexpected end of file.zIncomplete wav chunk.s   fmt Tr   r       @   `      z4Unsupported bit depth: the wav file has {}-bit data.s   facts   datazNo fmt chunk before datas   LIST   JUNK   Fakez-Chunk (non-data) not understood, skipping it.Nr   )r-   r   rD   rE   rF   rG   )rH   rI   )hasattropenrA   r5   r7   r   warningswarnr>   r   r   lenr,   r=   r<   closer8   )filenamer9   r   r@   r    Zfmt_chunk_receivedZdata_chunk_receivedr&   r*   r%   Zchunk_idZ	fmt_chunkr'   r:   r   r   r   r      sd    P















c             C   s0  t | dr| }n
t| d}|}z|jj}|dkpL|dkpL|dkoL|jjdks\td|j d}|d	7 }|d
7 }|d7 }|d7 }|dkrt}nt}|jdkrd}n
|j	d }|jjd }	||	d  | }
||	d  }t
jd||||
||	}|dkp|dks|d7 }|t
jdt|7 }||7 }|dkp0|dksT|d7 }|t
jdd|j	d 7 }t|d d d|j  dkr|td|j| |jd |jt
jd|j |jjdks|jjdkrtjdkr|j }t|| |j }|jd |jt
jd|d  W dt | ds |j  n
|jd X dS )a  
    Write a numpy array as a WAV file.

    Parameters
    ----------
    filename : string or open file handle
        Output wav file.
    rate : int
        The sample rate (in samples/sec).
    data : ndarray
        A 1-D or 2-D numpy array of either integer or float data-type.

    Notes
    -----
    * Writes a simple uncompressed WAV file.
    * To write multiple-channels, use a 2-D array of shape
      (Nsamples, Nchannels).
    * The bits-per-sample and PCM/float will be determined by the data-type.

    Common data types: [1]_

    =====================  ===========  ===========  =============
         WAV format            Min          Max       NumPy dtype
    =====================  ===========  ===========  =============
    32-bit floating-point  -1.0         +1.0         float32
    32-bit PCM             -2147483648  +2147483647  int32
    16-bit PCM             -32768       +32767       int16
    8-bit PCM              0            255          uint8
    =====================  ===========  ===========  =============

    Note that 8-bit PCM is unsigned.

    References
    ----------
    .. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming
       Interface and Data Specifications 1.0", section "Data Format of the
       Samples", August 1991
       http://www.tactilemedia.com/info/MCI_Control_Info.html

    Examples
    --------
    Create a 100Hz sine wave, sampled at 44100Hz.
    Write to 16-bit PCM, Mono.

    >>> from scipy.io.wavfile import write
    >>> samplerate = 44100; fs = 100
    >>> t = np.linspace(0., 1., samplerate)
    >>> amplitude = np.iinfo(np.int16).max
    >>> data = amplitude * np.sin(2. * np.pi * fs * t)
    >>> write("example.wav", samplerate, data)

    r   wbifur   zUnsupported data type '%s'    s   RIFFs       s   WAVEs   fmt r-   z<HHIIHHs     z<Is   factz<IIr   r   l    z!Data exceeds wave file size limits   datar   =bigNr-   )rJ   rK   r/   kinditemsizer   WAVE_FORMAT_IEEE_FLOATr5   ndimr3   r   packrN   nbytesr   	byteordersysZbyteswap_array_tofiler7   r8   rO   )rP   Zrater:   r   r'   ZdkindZheader_datar%   r&   r*   r(   r)   Zfmt_chunk_datar"   r   r   r   r   F  s^    5




 




c             C   s   | j |j jdj d S )Nb)r   Zravelviewr:   )r   r:   r   r   r   r`     s    r`   c             C   s   | j |j  d S )N)r   tostring)r   r:   r   r   r   r`     s    )F)F)__doc__
__future__r   r   r   r_   r6   r   rL   __all__UserWarningr   r5   rZ   r   r   r,   r<   r=   rA   r   r   version_infor`   r   r   r   r   <module>
   s.   C
#
 
