Advertisement
Guest User

Untitled

a guest
Jan 26th, 2015
182
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.67 KB | None | 0 0
  1. """Support utilities for COMP28512.
  2.  
  3. Place this in the same directory you use for COMP28512 notebooks.
  4.  
  5. Import it with:
  6. >>> from comp28512_utils import Audio
  7.  
  8. Use as:
  9. >>> Audio(data, sampling_rate, filename)
  10. To save the given data as a wav file and then load it
  11. into the notebook.
  12.  
  13. (C) University of Manchester 2015
  14. Author: Andrew Mundy
  15. """
  16. from __future__ import print_function
  17.  
  18. import base64
  19. from IPython import display
  20. import numpy as np
  21. from scipy.io import wavfile
  22.  
  23.  
  24. def Audio(data, rate, filename=None):
  25. """Save data to a file then play."""
  26. # Get a filename
  27. if filename is None:
  28. filename = "{:x}.wav".format(id(data))
  29.  
  30. # Check the data type
  31. if data.dtype.kind == 'f':
  32. # Data is floating point, assume that we can scale to 16 bits and save
  33. data = np.int16(data * 2**15)
  34.  
  35. # Write the data
  36. wavfile.write(filename, rate, data)
  37. print("Data written to {}.".format(filename))
  38.  
  39. # Read the data back in
  40. return audio_from_file(filename)
  41.  
  42.  
  43. def get_audio_from_file(filename):
  44. with open(filename, 'rb') as f:
  45. return "data:audio/wav;base64," + base64.encodestring(f.read())
  46.  
  47.  
  48. def audio_from_file(filename):
  49. """Play the data from a file"""
  50. # Return an HTML audio object with base64 encoded audio data included.
  51. # If file:// could return correct MIMEtypes this would be much nicer.
  52. with open(filename, 'rb') as f:
  53. return display.HTML(
  54. "<p><audio controls=\"controls\">"
  55. "<source src=\"{}\" type=\"audio/wav\" />"
  56. "Your browser does not support the AUDIO element. "
  57. "Open the relevant file to listen."
  58. "</audio></p>".format(get_audio_from_file(filename)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement