wave.py 18 KB

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