Barry Warsaw | 53f8fe4 | 2001-10-09 19:41:18 +0000 | [diff] [blame] | 1 | # Author: Anthony Baxter |
| 2 | |
| 3 | """Class representing audio/* type MIME documents. |
| 4 | """ |
| 5 | |
| 6 | import sndhdr |
| 7 | from cStringIO import StringIO |
| 8 | |
| 9 | import MIMEBase |
| 10 | import Errors |
| 11 | import Encoders |
| 12 | |
| 13 | |
| 14 | |
| 15 | _sndhdr_MIMEmap = {'au' : 'basic', |
| 16 | 'wav' :'x-wav', |
| 17 | 'aiff':'x-aiff', |
| 18 | 'aifc':'x-aiff', |
| 19 | } |
| 20 | |
| 21 | # There are others in sndhdr that don't have MIME types. :( |
| 22 | # Additional ones to be added to sndhdr? midi, mp3, realaudio, wma?? |
| 23 | def _whatsnd(data): |
| 24 | """Try to identify a sound file type. |
| 25 | |
| 26 | sndhdr.what() has a pretty cruddy interface, unfortunately. This is why |
| 27 | we re-do it here. It would be easier to reverse engineer the Unix 'file' |
| 28 | command and use the standard 'magic' file, as shipped with a modern Unix. |
| 29 | """ |
| 30 | hdr = data[:512] |
| 31 | fakefile = StringIO(hdr) |
| 32 | for testfn in sndhdr.tests: |
| 33 | res = testfn(hdr, fakefile) |
| 34 | if res is not None: |
| 35 | return _sndhdr_MIMEmap.get(res[0]) |
| 36 | return None |
| 37 | |
| 38 | |
| 39 | |
| 40 | class MIMEAudio(MIMEBase.MIMEBase): |
| 41 | """Class for generating audio/* MIME documents.""" |
| 42 | |
| 43 | def __init__(self, _audiodata, _subtype=None, |
| 44 | _encoder=Encoders.encode_base64, **_params): |
| 45 | """Create an audio/* type MIME document. |
| 46 | |
| 47 | _audiodata is a string containing the raw audio data. If this data |
| 48 | can be decoded by the standard Python `sndhdr' module, then the |
Greg Ward | 6253c2d | 2001-11-24 15:49:53 +0000 | [diff] [blame^] | 49 | subtype will be automatically included in the Content-Type: header. |
Barry Warsaw | 53f8fe4 | 2001-10-09 19:41:18 +0000 | [diff] [blame] | 50 | Otherwise, you can specify the specific audio subtype via the |
| 51 | _subtype parameter. If _subtype is not given, and no subtype can be |
| 52 | guessed, a TypeError is raised. |
| 53 | |
| 54 | _encoder is a function which will perform the actual encoding for |
| 55 | transport of the image data. It takes one argument, which is this |
| 56 | Image instance. It should use get_payload() and set_payload() to |
| 57 | change the payload to the encoded form. It should also add any |
| 58 | Content-Transfer-Encoding: or other headers to the message as |
| 59 | necessary. The default encoding is Base64. |
| 60 | |
| 61 | Any additional keyword arguments are passed to the base class |
| 62 | constructor, which turns them into parameters on the Content-Type: |
| 63 | header. |
| 64 | """ |
| 65 | if _subtype is None: |
| 66 | _subtype = _whatsnd(_audiodata) |
| 67 | if _subtype is None: |
| 68 | raise TypeError, 'Could not find audio MIME subtype' |
| 69 | MIMEBase.MIMEBase.__init__(self, 'audio', _subtype, **_params) |
| 70 | self.set_payload(_audiodata) |
| 71 | _encoder(self) |