wave.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  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 chunk import Chunk
  69. from collections import namedtuple
  70. import audioop
  71. import builtins
  72. import struct
  73. import sys
  74. __all__ = ["open", "Error", "Wave_read", "Wave_write"]
  75. class Error(Exception):
  76. pass
  77. WAVE_FORMAT_PCM = 0x0001
  78. _array_fmts = None, 'b', 'h', None, 'i'
  79. _wave_params = namedtuple('_wave_params',
  80. 'nchannels sampwidth framerate nframes comptype compname')
  81. class Wave_read:
  82. """Variables used in this class:
  83. These variables are available to the user though appropriate
  84. methods of this class:
  85. _file -- the open file with methods read(), close(), and seek()
  86. set through the __init__() method
  87. _nchannels -- the number of audio channels
  88. available through the getnchannels() method
  89. _nframes -- the number of audio frames
  90. available through the getnframes() method
  91. _sampwidth -- the number of bytes per audio sample
  92. available through the getsampwidth() method
  93. _framerate -- the sampling frequency
  94. available through the getframerate() method
  95. _comptype -- the AIFF-C compression type ('NONE' if AIFF)
  96. available through the getcomptype() method
  97. _compname -- the human-readable AIFF-C compression type
  98. available through the getcomptype() method
  99. _soundpos -- the position in the audio stream
  100. available through the tell() method, set through the
  101. setpos() method
  102. These variables are used internally only:
  103. _fmt_chunk_read -- 1 iff the FMT chunk has been read
  104. _data_seek_needed -- 1 iff positioned correctly in audio
  105. file for readframes()
  106. _data_chunk -- instantiation of a chunk class for the DATA chunk
  107. _framesize -- size of one frame in the file
  108. """
  109. def initfp(self, file):
  110. self._convert = None
  111. self._soundpos = 0
  112. self._file = Chunk(file, bigendian = 0)
  113. if self._file.getname() != b'RIFF':
  114. raise Error('file does not start with RIFF id')
  115. if self._file.read(4) != b'WAVE':
  116. raise Error('not a WAVE file')
  117. self._fmt_chunk_read = 0
  118. self._data_chunk = None
  119. while 1:
  120. self._data_seek_needed = 1
  121. try:
  122. chunk = Chunk(self._file, bigendian = 0)
  123. except EOFError:
  124. break
  125. chunkname = chunk.getname()
  126. if chunkname == b'fmt ':
  127. self._read_fmt_chunk(chunk)
  128. self._fmt_chunk_read = 1
  129. elif chunkname == b'data':
  130. if not self._fmt_chunk_read:
  131. raise Error('data chunk before fmt chunk')
  132. self._data_chunk = chunk
  133. self._nframes = chunk.chunksize // self._framesize
  134. self._data_seek_needed = 0
  135. break
  136. chunk.skip()
  137. if not self._fmt_chunk_read or not self._data_chunk:
  138. raise Error('fmt chunk and/or data chunk missing')
  139. def __init__(self, f):
  140. self._i_opened_the_file = None
  141. if isinstance(f, str):
  142. f = builtins.open(f, 'rb')
  143. self._i_opened_the_file = f
  144. # else, assume it is an open file object already
  145. try:
  146. self.initfp(f)
  147. except:
  148. if self._i_opened_the_file:
  149. f.close()
  150. raise
  151. def __del__(self):
  152. self.close()
  153. def __enter__(self):
  154. return self
  155. def __exit__(self, *args):
  156. self.close()
  157. #
  158. # User visible methods.
  159. #
  160. def getfp(self):
  161. return self._file
  162. def rewind(self):
  163. self._data_seek_needed = 1
  164. self._soundpos = 0
  165. def close(self):
  166. self._file = None
  167. file = self._i_opened_the_file
  168. if file:
  169. self._i_opened_the_file = None
  170. file.close()
  171. def tell(self):
  172. return self._soundpos
  173. def getnchannels(self):
  174. return self._nchannels
  175. def getnframes(self):
  176. return self._nframes
  177. def getsampwidth(self):
  178. return self._sampwidth
  179. def getframerate(self):
  180. return self._framerate
  181. def getcomptype(self):
  182. return self._comptype
  183. def getcompname(self):
  184. return self._compname
  185. def getparams(self):
  186. return _wave_params(self.getnchannels(), self.getsampwidth(),
  187. self.getframerate(), self.getnframes(),
  188. self.getcomptype(), self.getcompname())
  189. def getmarkers(self):
  190. return None
  191. def getmark(self, id):
  192. raise Error('no marks')
  193. def setpos(self, pos):
  194. if pos < 0 or pos > self._nframes:
  195. raise Error('position not in range')
  196. self._soundpos = pos
  197. self._data_seek_needed = 1
  198. def readframes(self, nframes):
  199. if self._data_seek_needed:
  200. self._data_chunk.seek(0, 0)
  201. pos = self._soundpos * self._framesize
  202. if pos:
  203. self._data_chunk.seek(pos, 0)
  204. self._data_seek_needed = 0
  205. if nframes == 0:
  206. return b''
  207. data = self._data_chunk.read(nframes * self._framesize)
  208. if self._sampwidth != 1 and sys.byteorder == 'big':
  209. data = audioop.byteswap(data, self._sampwidth)
  210. if self._convert and data:
  211. data = self._convert(data)
  212. self._soundpos = self._soundpos + len(data) // (self._nchannels * self._sampwidth)
  213. return data
  214. #
  215. # Internal methods.
  216. #
  217. def _read_fmt_chunk(self, chunk):
  218. try:
  219. wFormatTag, self._nchannels, self._framerate, dwAvgBytesPerSec, wBlockAlign = struct.unpack_from('<HHLLH', chunk.read(14))
  220. except struct.error:
  221. raise EOFError from None
  222. if wFormatTag == WAVE_FORMAT_PCM:
  223. try:
  224. sampwidth = struct.unpack_from('<H', chunk.read(2))[0]
  225. except struct.error:
  226. raise EOFError from None
  227. self._sampwidth = (sampwidth + 7) // 8
  228. if not self._sampwidth:
  229. raise Error('bad sample width')
  230. else:
  231. raise Error('unknown format: %r' % (wFormatTag,))
  232. if not self._nchannels:
  233. raise Error('bad # of channels')
  234. self._framesize = self._nchannels * self._sampwidth
  235. self._comptype = 'NONE'
  236. self._compname = 'not compressed'
  237. class Wave_write:
  238. """Variables used in this class:
  239. These variables are user settable through appropriate methods
  240. of this class:
  241. _file -- the open file with methods write(), close(), tell(), seek()
  242. set through the __init__() method
  243. _comptype -- the AIFF-C compression type ('NONE' in AIFF)
  244. set through the setcomptype() or setparams() method
  245. _compname -- the human-readable AIFF-C compression type
  246. set through the setcomptype() or setparams() method
  247. _nchannels -- the number of audio channels
  248. set through the setnchannels() or setparams() method
  249. _sampwidth -- the number of bytes per audio sample
  250. set through the setsampwidth() or setparams() method
  251. _framerate -- the sampling frequency
  252. set through the setframerate() or setparams() method
  253. _nframes -- the number of audio frames written to the header
  254. set through the setnframes() or setparams() method
  255. These variables are used internally only:
  256. _datalength -- the size of the audio samples written to the header
  257. _nframeswritten -- the number of frames actually written
  258. _datawritten -- the size of the audio samples actually written
  259. """
  260. def __init__(self, f):
  261. self._i_opened_the_file = None
  262. if isinstance(f, str):
  263. f = builtins.open(f, 'wb')
  264. self._i_opened_the_file = f
  265. try:
  266. self.initfp(f)
  267. except:
  268. if self._i_opened_the_file:
  269. f.close()
  270. raise
  271. def initfp(self, file):
  272. self._file = file
  273. self._convert = None
  274. self._nchannels = 0
  275. self._sampwidth = 0
  276. self._framerate = 0
  277. self._nframes = 0
  278. self._nframeswritten = 0
  279. self._datawritten = 0
  280. self._datalength = 0
  281. self._headerwritten = False
  282. def __del__(self):
  283. self.close()
  284. def __enter__(self):
  285. return self
  286. def __exit__(self, *args):
  287. self.close()
  288. #
  289. # User visible methods.
  290. #
  291. def setnchannels(self, nchannels):
  292. if self._datawritten:
  293. raise Error('cannot change parameters after starting to write')
  294. if nchannels < 1:
  295. raise Error('bad # of channels')
  296. self._nchannels = nchannels
  297. def getnchannels(self):
  298. if not self._nchannels:
  299. raise Error('number of channels not set')
  300. return self._nchannels
  301. def setsampwidth(self, sampwidth):
  302. if self._datawritten:
  303. raise Error('cannot change parameters after starting to write')
  304. if sampwidth < 1 or sampwidth > 4:
  305. raise Error('bad sample width')
  306. self._sampwidth = sampwidth
  307. def getsampwidth(self):
  308. if not self._sampwidth:
  309. raise Error('sample width not set')
  310. return self._sampwidth
  311. def setframerate(self, framerate):
  312. if self._datawritten:
  313. raise Error('cannot change parameters after starting to write')
  314. if framerate <= 0:
  315. raise Error('bad frame rate')
  316. self._framerate = int(round(framerate))
  317. def getframerate(self):
  318. if not self._framerate:
  319. raise Error('frame rate not set')
  320. return self._framerate
  321. def setnframes(self, nframes):
  322. if self._datawritten:
  323. raise Error('cannot change parameters after starting to write')
  324. self._nframes = nframes
  325. def getnframes(self):
  326. return self._nframeswritten
  327. def setcomptype(self, comptype, compname):
  328. if self._datawritten:
  329. raise Error('cannot change parameters after starting to write')
  330. if comptype not in ('NONE',):
  331. raise Error('unsupported compression type')
  332. self._comptype = comptype
  333. self._compname = compname
  334. def getcomptype(self):
  335. return self._comptype
  336. def getcompname(self):
  337. return self._compname
  338. def setparams(self, params):
  339. nchannels, sampwidth, framerate, nframes, comptype, compname = params
  340. if self._datawritten:
  341. raise Error('cannot change parameters after starting to write')
  342. self.setnchannels(nchannels)
  343. self.setsampwidth(sampwidth)
  344. self.setframerate(framerate)
  345. self.setnframes(nframes)
  346. self.setcomptype(comptype, compname)
  347. def getparams(self):
  348. if not self._nchannels or not self._sampwidth or not self._framerate:
  349. raise Error('not all parameters set')
  350. return _wave_params(self._nchannels, self._sampwidth, self._framerate,
  351. self._nframes, self._comptype, self._compname)
  352. def setmark(self, id, pos, name):
  353. raise Error('setmark() not supported')
  354. def getmark(self, id):
  355. raise Error('no marks')
  356. def getmarkers(self):
  357. return None
  358. def tell(self):
  359. return self._nframeswritten
  360. def writeframesraw(self, data):
  361. if not isinstance(data, (bytes, bytearray)):
  362. data = memoryview(data).cast('B')
  363. self._ensure_header_written(len(data))
  364. nframes = len(data) // (self._sampwidth * self._nchannels)
  365. if self._convert:
  366. data = self._convert(data)
  367. if self._sampwidth != 1 and sys.byteorder == 'big':
  368. data = audioop.byteswap(data, self._sampwidth)
  369. self._file.write(data)
  370. self._datawritten += len(data)
  371. self._nframeswritten = self._nframeswritten + nframes
  372. def writeframes(self, data):
  373. self.writeframesraw(data)
  374. if self._datalength != self._datawritten:
  375. self._patchheader()
  376. def close(self):
  377. try:
  378. if self._file:
  379. self._ensure_header_written(0)
  380. if self._datalength != self._datawritten:
  381. self._patchheader()
  382. self._file.flush()
  383. finally:
  384. self._file = None
  385. file = self._i_opened_the_file
  386. if file:
  387. self._i_opened_the_file = None
  388. file.close()
  389. #
  390. # Internal methods.
  391. #
  392. def _ensure_header_written(self, datasize):
  393. if not self._headerwritten:
  394. if not self._nchannels:
  395. raise Error('# channels not specified')
  396. if not self._sampwidth:
  397. raise Error('sample width not specified')
  398. if not self._framerate:
  399. raise Error('sampling rate not specified')
  400. self._write_header(datasize)
  401. def _write_header(self, initlength):
  402. assert not self._headerwritten
  403. self._file.write(b'RIFF')
  404. if not self._nframes:
  405. self._nframes = initlength // (self._nchannels * self._sampwidth)
  406. self._datalength = self._nframes * self._nchannels * self._sampwidth
  407. try:
  408. self._form_length_pos = self._file.tell()
  409. except (AttributeError, OSError):
  410. self._form_length_pos = None
  411. self._file.write(struct.pack('<L4s4sLHHLLHH4s',
  412. 36 + self._datalength, b'WAVE', b'fmt ', 16,
  413. WAVE_FORMAT_PCM, self._nchannels, self._framerate,
  414. self._nchannels * self._framerate * self._sampwidth,
  415. self._nchannels * self._sampwidth,
  416. self._sampwidth * 8, b'data'))
  417. if self._form_length_pos is not None:
  418. self._data_length_pos = self._file.tell()
  419. self._file.write(struct.pack('<L', self._datalength))
  420. self._headerwritten = True
  421. def _patchheader(self):
  422. assert self._headerwritten
  423. if self._datawritten == self._datalength:
  424. return
  425. curpos = self._file.tell()
  426. self._file.seek(self._form_length_pos, 0)
  427. self._file.write(struct.pack('<L', 36 + self._datawritten))
  428. self._file.seek(self._data_length_pos, 0)
  429. self._file.write(struct.pack('<L', self._datawritten))
  430. self._file.seek(curpos, 0)
  431. self._datalength = self._datawritten
  432. def open(f, mode=None):
  433. if mode is None:
  434. if hasattr(f, 'mode'):
  435. mode = f.mode
  436. else:
  437. mode = 'rb'
  438. if mode in ('r', 'rb'):
  439. return Wave_read(f)
  440. elif mode in ('w', 'wb'):
  441. return Wave_write(f)
  442. else:
  443. raise Error("mode must be 'r', 'rb', 'w', or 'wb'")