""" 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. """ import numpy from numpy.compat import asbytes import struct import warnings class WavFileWarning(UserWarning): pass _big_endian = False # 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 != 1 or size > 16): warnings.warn("Unfamiliar format bytes", 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, noc, bits): if _big_endian: fmt = '>i' else: fmt = ' 1: data = data.reshape(-1,noc) else: bytes = bits//8 if _big_endian: dtype = '>i%d' % bytes else: dtype = ' 1: data = data.reshape(-1,noc) return data def _read_riff_chunk(fid): global _big_endian str1 = fid.read(4) if str1 == asbytes('RIFX'): _big_endian = True elif str1 != asbytes('RIFF'): raise ValueError("Not a WAV file.") if _big_endian: fmt = '>I' else: fmt = '' or (data.dtype.byteorder == '=' and sys.byteorder == 'big'): data = data.byteswap() data.tofile(fid) # Determine file size and place it in correct # position at start of the file. size = fid.tell() fid.seek(4) fid.write(struct.pack('