In this Notebook, we show a couple of ways of working with audio data. This includes both playing the audio as well as working with the raw audio data as NumPy arrays.
First, we show how the Audio
class can be used to play raw audio data in a NumPy
array.
In [2]:
from audiodisplay import Audio
In [3]:
%pylab inline
Here we create a simple signal at A (440 Hz):
In [54]:
max_time = 3
f = 440.0
rate = 44100.0
times = np.arange(max_time*rate)/rate
signal = 2.0**16*np.sin(2*pi*f*times)/2.0
signal = signal.astype(np.int16)
The signal looks as you might expect:
In [58]:
plot(signal[0:500])
Out[58]:
We can simply pass the NumPy array and the sampling rate to the Audio
object to get
an HTML5 audio widget. This widget and audio data will be embedded in the notebook so
the audio can be played back later.
In [57]:
Audio(data=signal, rate=rate)
Out[57]:
Second, we show how to load audio data from a .wav
file. Here we have a 5 second
clip from J.S. Bach's Cello Suite #3 in C.
In [4]:
filename = 'data/Bach Cello Suite #3.wav'
In [5]:
Audio(filename=filename)
Out[5]:
Again, the widget and audio data are embedded in the notebook.
We can also read the raw audio data in as a NumPy array and perform some basic visualization.
In [6]:
from scipy.io import wavfile
In [7]:
rate, bach = wavfile.read(filename)
In [10]:
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(12,4))
ax1.plot(bach[:,0]); ax1.set_title('Raw audio signal');
ax1.locator_params(nbins=6)
ax2.specgram(bach[:,0]); ax2.set_title('Spectrogram');
ax2.locator_params(nbins=6)
In [ ]: