5. wave — Read and write WAV files¶
Contents
The wave module provides a convenient interface to the WAV sound format.
It does not support compression/decompression, but it does support mono/stereo.
The wave module defines the following function and exception:
-
wave.open(file[, mode])[source]¶ If file is a string, open the file by that name, otherwise treat it as a seekable file-like object. mode can be any of
'r','rb'- Read only mode.
'w','wb'- Write only mode.
Note that it does not allow read/write WAV files.
A mode of
'r'or'rb'returns aWave_readobject, while a mode of'w'or'wb'returns aWave_writeobject. If mode is omitted and a file-like object is passed as file,file.modeis used as the default value for mode (the'b'flag is still added if necessary).If you pass in a file-like object, the wave object will not close it when its
close()method is called; it is the caller’s responsibility to close the file object.
-
exception
wave.Error[source]¶ An error raised when something is impossible because it violates the WAV specification or hits an implementation deficiency.
5.1. Wave_read Objects¶
Wave_read objects, as returned by open(), have the following methods:
-
Wave_read.close()[source]¶ Close the stream if it was opened by
wave, and make the instance unusable. This is called automatically on object collection.
-
Wave_read.getcompname()[source]¶ Human-readable version of
getcomptype(). Usually'not compressed'parallels'NONE'.
-
Wave_read.getparams()[source]¶ Returns a tuple
(nchannels, sampwidth, framerate, nframes, comptype, compname), equivalent to output of theget*()methods.
The following two methods are defined for compatibility with the aifc
module, and don’t do anything interesting.
The following two methods define a term “position” which is compatible between them, and is otherwise implementation dependent.
5.2. Wave_write Objects¶
Wave_write objects, as returned by open(), have the following methods:
-
Wave_write.close()[source]¶ Make sure nframes is correct, and close the file if it was opened by
wave. This method is called upon object collection.
-
Wave_write.setnframes(n)[source]¶ Set the number of frames to n. This will be changed later if more frames are written.
-
Wave_write.setcomptype(type, name)[source]¶ Set the compression type and description. At the moment, only compression type
NONEis supported, meaning no compression.
-
Wave_write.setparams(tuple)[source]¶ The tuple should be
(nchannels, sampwidth, framerate, nframes, comptype, compname), with values valid for theset*()methods. Sets all parameters.
-
Wave_write.tell()[source]¶ Return current position in the file, with the same disclaimer for the
Wave_read.tell()andWave_read.setpos()methods.
Note that it is invalid to set any parameters after calling writeframes()
or writeframesraw(), and any attempt to do so will raise
wave.Error.