diff options
Diffstat (limited to 'Lib/sunau.py')
-rw-r--r-- | Lib/sunau.py | 50 |
1 files changed, 35 insertions, 15 deletions
diff --git a/Lib/sunau.py b/Lib/sunau.py index 5212370588e..5761390361c 100644 --- a/Lib/sunau.py +++ b/Lib/sunau.py @@ -51,7 +51,7 @@ This returns an instance of a class with the following public methods: getcomptype() -- returns compression type ('NONE' or 'ULAW') getcompname() -- returns human-readable version of compression type ('not compressed' matches 'NONE') - getparams() -- returns a tuple consisting of all of the + getparams() -- returns a namedtuple consisting of all of the above in the above order getmarkers() -- returns None (for compatibility with the aifc module) @@ -103,6 +103,11 @@ The close() method is called automatically when the class instance is destroyed. """ +from collections import namedtuple + +_sunau_params = namedtuple('_sunau_params', + 'nchannels sampwidth framerate nframes comptype compname') + # from <multimedia/audio_filehdr.h> AUDIO_FILE_MAGIC = 0x2e736e64 AUDIO_FILE_ENCODING_MULAW_8 = 1 @@ -163,6 +168,12 @@ class Au_read: if self._file: self.close() + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + def initfp(self, file): self._file = file self._soundpos = 0 @@ -246,9 +257,9 @@ class Au_read: return 'not compressed' def getparams(self): - return self.getnchannels(), self.getsampwidth(), \ - self.getframerate(), self.getnframes(), \ - self.getcomptype(), self.getcompname() + return _sunau_params(self.getnchannels(), self.getsampwidth(), + self.getframerate(), self.getnframes(), + self.getcomptype(), self.getcompname()) def getmarkers(self): return None @@ -307,6 +318,12 @@ class Au_write: self.close() self._file = None + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + def initfp(self, file): self._file = file self._framerate = 0 @@ -390,9 +407,9 @@ class Au_write: self.setcomptype(comptype, compname) def getparams(self): - return self.getnchannels(), self.getsampwidth(), \ - self.getframerate(), self.getnframes(), \ - self.getcomptype(), self.getcompname() + return _sunau_params(self.getnchannels(), self.getsampwidth(), + self.getframerate(), self.getnframes(), + self.getcomptype(), self.getcompname()) def tell(self): return self._nframeswritten @@ -414,14 +431,17 @@ class Au_write: self._patchheader() def close(self): - self._ensure_header_written() - if self._nframeswritten != self._nframes or \ - self._datalength != self._datawritten: - self._patchheader() - self._file.flush() - if self._opened and self._file: - self._file.close() - self._file = None + if self._file: + try: + self._ensure_header_written() + if self._nframeswritten != self._nframes or \ + self._datalength != self._datawritten: + self._patchheader() + self._file.flush() + finally: + if self._opened and self._file: + self._file.close() + self._file = None # # private methods |