wave.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653
  1. """Stuff to parse WAVE files.
  2. Usage.
  3. Reading WAVE files:
  4. f = wave.open(file, 'r')
  5. where file is either the name of a file or an open file pointer.
  6. The open file pointer must have methods read(), seek(), and close().
  7. When the setpos() and rewind() methods are not used, the seek()
  8. method is not necessary.
  9. This returns an instance of a class with the following public methods:
  10. getnchannels() -- returns number of audio channels (1 for
  11. mono, 2 for stereo)
  12. getsampwidth() -- returns sample width in bytes
  13. getframerate() -- returns sampling frequency
  14. getnframes() -- returns number of audio frames
  15. getcomptype() -- returns compression type ('NONE' for linear samples)
  16. getcompname() -- returns human-readable version of
  17. compression type ('not compressed' linear samples)
  18. getparams() -- returns a namedtuple consisting of all of the
  19. above in the above order
  20. getmarkers() -- returns None (for compatibility with the
  21. aifc module)
  22. getmark(id) -- raises an error since the mark does not
  23. exist (for compatibility with the aifc module)
  24. readframes(n) -- returns at most n frames of audio
  25. rewind() -- rewind to the beginning of the audio stream
  26. setpos(pos) -- seek to the specified position
  27. tell() -- return the current position
  28. close() -- close the instance (make it unusable)
  29. The position returned by tell() and the position given to setpos()
  30. are compatible and have nothing to do with the actual position in the
  31. file.
  32. The close() method is called automatically when the class instance
  33. is destroyed.
  34. Writing WAVE files:
  35. f = wave.open(file, 'w')
  36. where file is either the name of a file or an open file pointer.
  37. The open file pointer must have methods write(), tell(), seek(), and
  38. close().
  39. This returns an instance of a class with the following public methods:
  40. setnchannels(n) -- set the number of channels
  41. setsampwidth(n) -- set the sample width
  42. setframerate(n) -- set the frame rate
  43. setnframes(n) -- set the number of frames
  44. setcomptype(type, name)
  45. -- set the compression type and the
  46. human-readable compression type
  47. setparams(tuple)
  48. -- set all parameters at once
  49. tell() -- return current position in output file
  50. writeframesraw(data)
  51. -- write audio frames without patching up the
  52. file header
  53. writeframes(data)
  54. -- write audio frames and patch up the file header
  55. close() -- patch up the file header and close the
  56. output file
  57. You should set the parameters before the first writeframesraw or
  58. writeframes. The total number of frames does not need to be set,
  59. but when it is set to the correct value, the header does not have to
  60. be patched up.
  61. It is best to first set all parameters, perhaps possibly the
  62. compression type, and then write audio frames using writeframesraw.
  63. When all frames have been written, either call writeframes(b'') or
  64. close() to patch up the sizes in the header.
  65. The close() method is called automatically when the class instance
  66. is destroyed.
  67. """
  68. from collections import namedtuple
  69. import builtins
  70. import struct
  71. import sys
  72. __all__ = ["open", "Error", "Wave_read", "Wave_write"]
  73. class Error(Exception):
  74. pass
  75. WAVE_FORMAT_PCM = 0x0001
  76. WAVE_FORMAT_EXTENSIBLE = 0xFFFE
  77. # Derived from uuid.UUID("00000001-0000-0010-8000-00aa00389b71").bytes_le
  78. KSDATAFORMAT_SUBTYPE_PCM = b'\x01\x00\x00\x00\x00\x00\x10\x00\x80\x00\x00\xaa\x008\x9bq'
  79. _array_fmts = None, 'b', 'h', None, 'i'
  80. _wave_params = namedtuple('_wave_params',
  81. 'nchannels sampwidth framerate nframes comptype compname')
  82. def _byteswap(data, width):
  83. swapped_data = bytearray(len(data))
  84. for i in range(0, len(data), width):
  85. for j in range(width):
  86. swapped_data[i + width - 1 - j] = data[i + j]
  87. return bytes(swapped_data)
  88. class _Chunk:
  89. def __init__(self, file, align=True, bigendian=True, inclheader=False):
  90. self.closed = False
  91. self.align = align # whether to align to word (2-byte) boundaries
  92. if bigendian:
  93. strflag = '>'
  94. else:
  95. strflag = '<'
  96. self.file = file
  97. self.chunkname = file.read(4)
  98. if len(self.chunkname) < 4:
  99. raise EOFError
  100. try:
  101. self.chunksize = struct.unpack_from(strflag+'L', file.read(4))[0]
  102. except struct.error:
  103. raise EOFError from None
  104. if inclheader:
  105. self.chunksize = self.chunksize - 8 # subtract header
  106. self.size_read = 0
  107. try:
  108. self.offset = self.file.tell()
  109. except (AttributeError, OSError):
  110. self.seekable = False
  111. else:
  112. self.seekable = True
  113. def getname(self):
  114. """Return the name (ID) of the current chunk."""
  115. return self.chunkname
  116. def close(self):
  117. if not self.closed:
  118. try:
  119. self.skip()
  120. finally:
  121. self.closed = True
  122. def seek(self, pos, whence=0):
  123. """Seek to specified position into the chunk.
  124. Default position is 0 (start of chunk).
  125. If the file is not seekable, this will result in an error.
  126. """
  127. if self.closed:
  128. raise ValueError("I/O operation on closed file")
  129. if not self.seekable:
  130. raise OSError("cannot seek")
  131. if whence == 1:
  132. pos = pos + self.size_read
  133. elif whence == 2:
  134. pos = pos + self.chunksize
  135. if pos < 0 or pos > self.chunksize:
  136. raise RuntimeError
  137. self.file.seek(self.offset + pos, 0)
  138. self.size_read = pos
  139. def tell(self):
  140. if self.closed:
  141. raise ValueError("I/O operation on closed file")
  142. return self.size_read
  143. def read(self, size=-1):
  144. """Read at most size bytes from the chunk.
  145. If size is omitted or negative, read until the end
  146. of the chunk.
  147. """
  148. if self.closed:
  149. raise ValueError("I/O operation on closed file")
  150. if self.size_read >= self.chunksize:
  151. return b''
  152. if size < 0:
  153. size = self.chunksize - self.size_read
  154. if size > self.chunksize - self.size_read:
  155. size = self.chunksize - self.size_read
  156. data = self.file.read(size)
  157. self.size_read = self.size_read + len(data)
  158. if self.size_read == self.chunksize and \
  159. self.align and \
  160. (self.chunksize & 1):
  161. dummy = self.file.read(1)
  162. self.size_read = self.size_read + len(dummy)
  163. return data
  164. def skip(self):
  165. """Skip the rest of the chunk.
  166. If you are not interested in the contents of the chunk,
  167. this method should be called so that the file points to
  168. the start of the next chunk.
  169. """
  170. if self.closed:
  171. raise ValueError("I/O operation on closed file")
  172. if self.seekable:
  173. try:
  174. n = self.chunksize - self.size_read
  175. # maybe fix alignment
  176. if self.align and (self.chunksize & 1):
  177. n = n + 1
  178. self.file.seek(n, 1)
  179. self.size_read = self.size_read + n
  180. return
  181. except OSError:
  182. pass
  183. while self.size_read < self.chunksize:
  184. n = min(8192, self.chunksize - self.size_read)
  185. dummy = self.read(n)
  186. if not dummy:
  187. raise EOFError
  188. class Wave_read:
  189. """Variables used in this class:
  190. These variables are available to the user though appropriate
  191. methods of this class:
  192. _file -- the open file with methods read(), close(), and seek()
  193. set through the __init__() method
  194. _nchannels -- the number of audio channels
  195. available through the getnchannels() method
  196. _nframes -- the number of audio frames
  197. available through the getnframes() method
  198. _sampwidth -- the number of bytes per audio sample
  199. available through the getsampwidth() method
  200. _framerate -- the sampling frequency
  201. available through the getframerate() method
  202. _comptype -- the AIFF-C compression type ('NONE' if AIFF)
  203. available through the getcomptype() method
  204. _compname -- the human-readable AIFF-C compression type
  205. available through the getcomptype() method
  206. _soundpos -- the position in the audio stream
  207. available through the tell() method, set through the
  208. setpos() method
  209. These variables are used internally only:
  210. _fmt_chunk_read -- 1 iff the FMT chunk has been read
  211. _data_seek_needed -- 1 iff positioned correctly in audio
  212. file for readframes()
  213. _data_chunk -- instantiation of a chunk class for the DATA chunk
  214. _framesize -- size of one frame in the file
  215. """
  216. def initfp(self, file):
  217. self._convert = None
  218. self._soundpos = 0
  219. self._file = _Chunk(file, bigendian = 0)
  220. if self._file.getname() != b'RIFF':
  221. raise Error('file does not start with RIFF id')
  222. if self._file.read(4) != b'WAVE':
  223. raise Error('not a WAVE file')
  224. self._fmt_chunk_read = 0
  225. self._data_chunk = None
  226. while 1:
  227. self._data_seek_needed = 1
  228. try:
  229. chunk = _Chunk(self._file, bigendian = 0)
  230. except EOFError:
  231. break
  232. chunkname = chunk.getname()
  233. if chunkname == b'fmt ':
  234. self._read_fmt_chunk(chunk)
  235. self._fmt_chunk_read = 1
  236. elif chunkname == b'data':
  237. if not self._fmt_chunk_read:
  238. raise Error('data chunk before fmt chunk')
  239. self._data_chunk = chunk
  240. self._nframes = chunk.chunksize // self._framesize
  241. self._data_seek_needed = 0
  242. break
  243. chunk.skip()
  244. if not self._fmt_chunk_read or not self._data_chunk:
  245. raise Error('fmt chunk and/or data chunk missing')
  246. def __init__(self, f):
  247. self._i_opened_the_file = None
  248. if isinstance(f, str):
  249. f = builtins.open(f, 'rb')
  250. self._i_opened_the_file = f
  251. # else, assume it is an open file object already
  252. try:
  253. self.initfp(f)
  254. except:
  255. if self._i_opened_the_file:
  256. f.close()
  257. raise
  258. def __del__(self):
  259. self.close()
  260. def __enter__(self):
  261. return self
  262. def __exit__(self, *args):
  263. self.close()
  264. #
  265. # User visible methods.
  266. #
  267. def getfp(self):
  268. return self._file
  269. def rewind(self):
  270. self._data_seek_needed = 1
  271. self._soundpos = 0
  272. def close(self):
  273. self._file = None
  274. file = self._i_opened_the_file
  275. if file:
  276. self._i_opened_the_file = None
  277. file.close()
  278. def tell(self):
  279. return self._soundpos
  280. def getnchannels(self):
  281. return self._nchannels
  282. def getnframes(self):
  283. return self._nframes
  284. def getsampwidth(self):
  285. return self._sampwidth
  286. def getframerate(self):
  287. return self._framerate
  288. def getcomptype(self):
  289. return self._comptype
  290. def getcompname(self):
  291. return self._compname
  292. def getparams(self):
  293. return _wave_params(self.getnchannels(), self.getsampwidth(),
  294. self.getframerate(), self.getnframes(),
  295. self.getcomptype(), self.getcompname())
  296. def getmarkers(self):
  297. return None
  298. def getmark(self, id):
  299. raise Error('no marks')
  300. def setpos(self, pos):
  301. if pos < 0 or pos > self._nframes:
  302. raise Error('position not in range')
  303. self._soundpos = pos
  304. self._data_seek_needed = 1
  305. def readframes(self, nframes):
  306. if self._data_seek_needed:
  307. self._data_chunk.seek(0, 0)
  308. pos = self._soundpos * self._framesize
  309. if pos:
  310. self._data_chunk.seek(pos, 0)
  311. self._data_seek_needed = 0
  312. if nframes == 0:
  313. return b''
  314. data = self._data_chunk.read(nframes * self._framesize)
  315. if self._sampwidth != 1 and sys.byteorder == 'big':
  316. data = _byteswap(data, self._sampwidth)
  317. if self._convert and data:
  318. data = self._convert(data)
  319. self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth)
  320. return data
  321. #
  322. # Internal methods.
  323. #
  324. def _read_fmt_chunk(self, chunk):
  325. try:
  326. wFormatTag, self._nchannels, self._framerate, dwAvgBytesPerSec, wBlockAlign = struct.unpack_from('<HHLLH', chunk.read(14))
  327. except struct.error:
  328. raise EOFError from None
  329. if wFormatTag != WAVE_FORMAT_PCM and wFormatTag != WAVE_FORMAT_EXTENSIBLE:
  330. raise Error('unknown format: %r' % (wFormatTag,))
  331. try:
  332. sampwidth = struct.unpack_from('<H', chunk.read(2))[0]
  333. except struct.error:
  334. raise EOFError from None
  335. if wFormatTag == WAVE_FORMAT_EXTENSIBLE:
  336. try:
  337. cbSize, wValidBitsPerSample, dwChannelMask = struct.unpack_from('<HHL', chunk.read(8))
  338. # Read the entire UUID from the chunk
  339. SubFormat = chunk.read(16)
  340. if len(SubFormat) < 16:
  341. raise EOFError
  342. except struct.error:
  343. raise EOFError from None
  344. if SubFormat != KSDATAFORMAT_SUBTYPE_PCM:
  345. try:
  346. import uuid
  347. subformat_msg = f'unknown extended format: {uuid.UUID(bytes_le=SubFormat)}'
  348. except Exception:
  349. subformat_msg = 'unknown extended format'
  350. raise Error(subformat_msg)
  351. self._sampwidth = (sampwidth + 7) // 8
  352. if not self._sampwidth:
  353. raise Error('bad sample width')
  354. if not self._nchannels:
  355. raise Error('bad # of channels')
  356. self._framesize = self._nchannels * self._sampwidth
  357. self._comptype = 'NONE'
  358. self._compname = 'not compressed'
  359. class Wave_write:
  360. """Variables used in this class:
  361. These variables are user settable through appropriate methods
  362. of this class:
  363. _file -- the open file with methods write(), close(), tell(), seek()
  364. set through the __init__() method
  365. _comptype -- the AIFF-C compression type ('NONE' in AIFF)
  366. set through the setcomptype() or setparams() method
  367. _compname -- the human-readable AIFF-C compression type
  368. set through the setcomptype() or setparams() method
  369. _nchannels -- the number of audio channels
  370. set through the setnchannels() or setparams() method
  371. _sampwidth -- the number of bytes per audio sample
  372. set through the setsampwidth() or setparams() method
  373. _framerate -- the sampling frequency
  374. set through the setframerate() or setparams() method
  375. _nframes -- the number of audio frames written to the header
  376. set through the setnframes() or setparams() method
  377. These variables are used internally only:
  378. _datalength -- the size of the audio samples written to the header
  379. _nframeswritten -- the number of frames actually written
  380. _datawritten -- the size of the audio samples actually written
  381. """
  382. def __init__(self, f):
  383. self._i_opened_the_file = None
  384. if isinstance(f, str):
  385. f = builtins.open(f, 'wb')
  386. self._i_opened_the_file = f
  387. try:
  388. self.initfp(f)
  389. except:
  390. if self._i_opened_the_file:
  391. f.close()
  392. raise
  393. def initfp(self, file):
  394. self._file = file
  395. self._convert = None
  396. self._nchannels = 0
  397. self._sampwidth = 0
  398. self._framerate = 0
  399. self._nframes = 0
  400. self._nframeswritten = 0
  401. self._datawritten = 0
  402. self._datalength = 0
  403. self._headerwritten = False
  404. def __del__(self):
  405. self.close()
  406. def __enter__(self):
  407. return self
  408. def __exit__(self, *args):
  409. self.close()
  410. #
  411. # User visible methods.
  412. #
  413. def setnchannels(self, nchannels):
  414. if self._datawritten:
  415. raise Error('cannot change parameters after starting to write')
  416. if nchannels < 1:
  417. raise Error('bad # of channels')
  418. self._nchannels = nchannels
  419. def getnchannels(self):
  420. if not self._nchannels:
  421. raise Error('number of channels not set')
  422. return self._nchannels
  423. def setsampwidth(self, sampwidth):
  424. if self._datawritten:
  425. raise Error('cannot change parameters after starting to write')
  426. if sampwidth < 1 or sampwidth > 4:
  427. raise Error('bad sample width')
  428. self._sampwidth = sampwidth
  429. def getsampwidth(self):
  430. if not self._sampwidth:
  431. raise Error('sample width not set')
  432. return self._sampwidth
  433. def setframerate(self, framerate):
  434. if self._datawritten:
  435. raise Error('cannot change parameters after starting to write')
  436. if framerate <= 0:
  437. raise Error('bad frame rate')
  438. self._framerate = int(round(framerate))
  439. def getframerate(self):
  440. if not self._framerate:
  441. raise Error('frame rate not set')
  442. return self._framerate
  443. def setnframes(self, nframes):
  444. if self._datawritten:
  445. raise Error('cannot change parameters after starting to write')
  446. self._nframes = nframes
  447. def getnframes(self):
  448. return self._nframeswritten
  449. def setcomptype(self, comptype, compname):
  450. if self._datawritten:
  451. raise Error('cannot change parameters after starting to write')
  452. if comptype not in ('NONE',):
  453. raise Error('unsupported compression type')
  454. self._comptype = comptype
  455. self._compname = compname
  456. def getcomptype(self):
  457. return self._comptype
  458. def getcompname(self):
  459. return self._compname
  460. def setparams(self, params):
  461. nchannels, sampwidth, framerate, nframes, comptype, compname = params
  462. if self._datawritten:
  463. raise Error('cannot change parameters after starting to write')
  464. self.setnchannels(nchannels)
  465. self.setsampwidth(sampwidth)
  466. self.setframerate(framerate)
  467. self.setnframes(nframes)
  468. self.setcomptype(comptype, compname)
  469. def getparams(self):
  470. if not self._nchannels or not self._sampwidth or not self._framerate:
  471. raise Error('not all parameters set')
  472. return _wave_params(self._nchannels, self._sampwidth, self._framerate,
  473. self._nframes, self._comptype, self._compname)
  474. def setmark(self, id, pos, name):
  475. raise Error('setmark() not supported')
  476. def getmark(self, id):
  477. raise Error('no marks')
  478. def getmarkers(self):
  479. return None
  480. def tell(self):
  481. return self._nframeswritten
  482. def writeframesraw(self, data):
  483. if not isinstance(data, (bytes, bytearray)):
  484. data = memoryview(data).cast('B')
  485. self._ensure_header_written(len(data))
  486. nframes = len(data) // (self._sampwidth * self._nchannels)
  487. if self._convert:
  488. data = self._convert(data)
  489. if self._sampwidth != 1 and sys.byteorder == 'big':
  490. data = _byteswap(data, self._sampwidth)
  491. self._file.write(data)
  492. self._datawritten += len(data)
  493. self._nframeswritten = self._nframeswritten + nframes
  494. def writeframes(self, data):
  495. self.writeframesraw(data)
  496. if self._datalength != self._datawritten:
  497. self._patchheader()
  498. def close(self):
  499. try:
  500. if self._file:
  501. self._ensure_header_written(0)
  502. if self._datalength != self._datawritten:
  503. self._patchheader()
  504. self._file.flush()
  505. finally:
  506. self._file = None
  507. file = self._i_opened_the_file
  508. if file:
  509. self._i_opened_the_file = None
  510. file.close()
  511. #
  512. # Internal methods.
  513. #
  514. def _ensure_header_written(self, datasize):
  515. if not self._headerwritten:
  516. if not self._nchannels:
  517. raise Error('# channels not specified')
  518. if not self._sampwidth:
  519. raise Error('sample width not specified')
  520. if not self._framerate:
  521. raise Error('sampling rate not specified')
  522. self._write_header(datasize)
  523. def _write_header(self, initlength):
  524. assert not self._headerwritten
  525. self._file.write(b'RIFF')
  526. if not self._nframes:
  527. self._nframes = initlength // (self._nchannels * self._sampwidth)
  528. self._datalength = self._nframes * self._nchannels * self._sampwidth
  529. try:
  530. self._form_length_pos = self._file.tell()
  531. except (AttributeError, OSError):
  532. self._form_length_pos = None
  533. self._file.write(struct.pack('<L4s4sLHHLLHH4s',
  534. 36 + self._datalength, b'WAVE', b'fmt ', 16,
  535. WAVE_FORMAT_PCM, self._nchannels, self._framerate,
  536. self._nchannels * self._framerate * self._sampwidth,
  537. self._nchannels * self._sampwidth,
  538. self._sampwidth * 8, b'data'))
  539. if self._form_length_pos is not None:
  540. self._data_length_pos = self._file.tell()
  541. self._file.write(struct.pack('<L', self._datalength))
  542. self._headerwritten = True
  543. def _patchheader(self):
  544. assert self._headerwritten
  545. if self._datawritten == self._datalength:
  546. return
  547. curpos = self._file.tell()
  548. self._file.seek(self._form_length_pos, 0)
  549. self._file.write(struct.pack('<L', 36 + self._datawritten))
  550. self._file.seek(self._data_length_pos, 0)
  551. self._file.write(struct.pack('<L', self._datawritten))
  552. self._file.seek(curpos, 0)
  553. self._datalength = self._datawritten
  554. def open(f, mode=None):
  555. if mode is None:
  556. if hasattr(f, 'mode'):
  557. mode = f.mode
  558. else:
  559. mode = 'rb'
  560. if mode in ('r', 'rb'):
  561. return Wave_read(f)
  562. elif mode in ('w', 'wb'):
  563. return Wave_write(f)
  564. else:
  565. raise Error("mode must be 'r', 'rb', 'w', or 'wb'")