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