PageRenderTime 51ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/lib-python/2.7/wave.py

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