Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- """Support utilities for COMP28512.
- Place this in the same directory you use for COMP28512 notebooks.
- Import it with:
- >>> from comp28512_utils import Audio
- Use as:
- >>> Audio(data, sampling_rate, filename)
- To save the given data as a wav file and then load it
- into the notebook.
- (C) University of Manchester 2015
- Author: Andrew Mundy
- """
- from __future__ import print_function
- import base64
- from IPython import display
- import numpy as np
- from scipy.io import wavfile
- def Audio(data, rate, filename=None):
- """Save data to a file then play."""
- # Get a filename
- if filename is None:
- filename = "{:x}.wav".format(id(data))
- # Check the data type
- if data.dtype.kind == 'f':
- # Data is floating point, assume that we can scale to 16 bits and save
- data = np.int16(data * 2**15)
- # Write the data
- wavfile.write(filename, rate, data)
- print("Data written to {}.".format(filename))
- # Read the data back in
- return audio_from_file(filename)
- def get_audio_from_file(filename):
- with open(filename, 'rb') as f:
- return "data:audio/wav;base64," + base64.encodestring(f.read())
- def audio_from_file(filename):
- """Play the data from a file"""
- # Return an HTML audio object with base64 encoded audio data included.
- # If file:// could return correct MIMEtypes this would be much nicer.
- with open(filename, 'rb') as f:
- return display.HTML(
- "<p><audio controls=\"controls\">"
- "<source src=\"{}\" type=\"audio/wav\" />"
- "Your browser does not support the AUDIO element. "
- "Open the relevant file to listen."
- "</audio></p>".format(get_audio_from_file(filename)))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement