""" 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. """ from __future__ import absolute_import, division, print_function import os import struct import sys import warnings import numpy class WavFileWarning(UserWarning): pass _big_endian = False WAVE_FORMAT_PCM = 0x0001 WAVE_FORMAT_IEEE_FLOAT = 0x0003 WAVE_FORMAT_EXTENSIBLE = 0xFFFE KNOWN_WAVE_FORMATS = (WAVE_FORMAT_PCM, WAVE_FORMAT_IEEE_FLOAT) # assumes file pointer is immediately # after the 'fmt ' id def _read_fmt_chunk(fid): if _big_endian: fmt = ">" else: fmt = "<" res = struct.unpack(fmt + "iHHIIHH", fid.read(20)) size, comp, noc, rate, sbytes, ba, bits = res if comp not in KNOWN_WAVE_FORMATS or size > 16: comp = WAVE_FORMAT_PCM warnings.warn("Unknown wave file format", WavFileWarning) if size > 16: fid.read(size - 16) return size, comp, noc, rate, sbytes, ba, bits # assumes file pointer is immediately # after the 'data' id def _read_data_chunk(fid, comp, noc, bits, mmap=False): if _big_endian: fmt = ">i" else: fmt = " 1: data = data.reshape(-1, noc) return data def _skip_unknown_chunk(fid): if _big_endian: fmt = ">i" else: fmt = "" or ( data.dtype.byteorder == "=" and sys.byteorder == "big" ): data = data.byteswap() _array_tofile(fid, data) # Determine file size and place it in correct # position at start of the file (replacing the 4 bytes of zeros) size = fid.tell() fid.seek(4) fid.write(struct.pack("= 3: def _array_tofile(fid, data): # ravel gives a c-contiguous buffer fid.write(data.ravel().view("b").data) else: def _array_tofile(fid, data): fid.write(data.tostring())