wave.py 21 KB

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