wave.py 18 KB

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