1# Copyright (C) 2001-2007 Python Software Foundation 2# Author: Anthony Baxter 3# Contact: email-sig@python.org 4 5"""Class representing audio/* type MIME documents.""" 6 7__all__ = ['MIMEAudio'] 8 9from email import encoders 10from email.mime.nonmultipart import MIMENonMultipart 11 12 13class MIMEAudio(MIMENonMultipart): 14 """Class for generating audio/* MIME documents.""" 15 16 def __init__(self, _audiodata, _subtype=None, 17 _encoder=encoders.encode_base64, *, policy=None, **_params): 18 """Create an audio/* type MIME document. 19 20 _audiodata contains the bytes for the raw audio data. If this data 21 can be decoded as au, wav, aiff, or aifc, then the 22 subtype will be automatically included in the Content-Type header. 23 Otherwise, you can specify the specific audio subtype via the 24 _subtype parameter. If _subtype is not given, and no subtype can be 25 guessed, a TypeError is raised. 26 27 _encoder is a function which will perform the actual encoding for 28 transport of the image data. It takes one argument, which is this 29 Image instance. It should use get_payload() and set_payload() to 30 change the payload to the encoded form. It should also add any 31 Content-Transfer-Encoding or other headers to the message as 32 necessary. The default encoding is Base64. 33 34 Any additional keyword arguments are passed to the base class 35 constructor, which turns them into parameters on the Content-Type 36 header. 37 """ 38 if _subtype is None: 39 _subtype = _what(_audiodata) 40 if _subtype is None: 41 raise TypeError('Could not find audio MIME subtype') 42 MIMENonMultipart.__init__(self, 'audio', _subtype, policy=policy, 43 **_params) 44 self.set_payload(_audiodata) 45 _encoder(self) 46 47 48_rules = [] 49 50 51# Originally from the sndhdr module. 52# 53# There are others in sndhdr that don't have MIME types. :( 54# Additional ones to be added to sndhdr? midi, mp3, realaudio, wma?? 55def _what(data): 56 # Try to identify a sound file type. 57 # 58 # sndhdr.what() had a pretty cruddy interface, unfortunately. This is why 59 # we re-do it here. It would be easier to reverse engineer the Unix 'file' 60 # command and use the standard 'magic' file, as shipped with a modern Unix. 61 for testfn in _rules: 62 if res := testfn(data): 63 return res 64 else: 65 return None 66 67 68def rule(rulefunc): 69 _rules.append(rulefunc) 70 return rulefunc 71 72 73@rule 74def _aiff(h): 75 if not h.startswith(b'FORM'): 76 return None 77 if h[8:12] in {b'AIFC', b'AIFF'}: 78 return 'x-aiff' 79 else: 80 return None 81 82 83@rule 84def _au(h): 85 if h.startswith(b'.snd'): 86 return 'basic' 87 else: 88 return None 89 90 91@rule 92def _wav(h): 93 # 'RIFF' <len> 'WAVE' 'fmt ' <len> 94 if not h.startswith(b'RIFF') or h[8:12] != b'WAVE' or h[12:16] != b'fmt ': 95 return None 96 else: 97 return "x-wav" 98