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