wave.py 18 KB

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