audio.py 2.7 KB

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