In [79]:
import numpy as np
from scipy.io.wavfile import read
import matplotlib.pyplot as plt
from __future__ import division
%matplotlib inline

# Read the file
sample_frequency, data = read('/Users/Nick/Downloads/piano2.wav')

# Normalize the data (tonal intensity per channel)
# print(data.dtype)
data_type = 16 # mapped to 2 ** 15 possible values
sound = data / (2.0 ** (data_type - 1)) 

# Find song sample parameters
n_samples = sound.shape[0]
n_channels = sound.shape[1]
duration = n_samples / sample_frequency
print("The song is {} seconds long at a sample rate of {}Hz.".format(duration, sample_frequency))
t = np.arange(0, duration, 1/sample_frequency)
print(t[50000])
print(fft(sound[50000:50001,0]))

# Plot the tone
for chan in range(n_channels):
    ax = plt.subplot(n_channels, 1, chan + 1)
    ax.plot(t, sound[:,chan])
    ax.set_title('Tone of Channel {}'.format(chan))

fig = plt.gcf()
fig.set_size_inches(13,8)
plt.show()


The song is 6.3065 seconds long at a sample rate of 48000Hz.
1.04166666667
[-0.0071106+0.j]

In [64]:
from scipy.fftpack import fft

# Find the frequencies in the sound sample
p = fft(sound) 
print(sound.shape)

n_unique_pts = np.ceil((n_samples + 1) / 2.0)
p = p[0:n_unique_pts]
p = abs(p)
p = p / float(n_samples)
p = p ** 2

if n_samples % 2 > 0: # we've got odd number of points fft
    p[1:len(p)] = p[1:len(p)] * 2
else: # we've got even number of points fft
    p[1:len(p) -1] = p[1:len(p) - 1] * 2

freqArray = np.arange(0, n_unique_pts, 1.0) * (sample_frequency / n_samples);

for chan in range(n_channels):
    ax = plt.subplot(n_channels, 1, chan + 1)
    freq = 10*np.log10(p[:,chan].clip(min=10 ** -17))
    ax.plot(freqArray/1000, freq)
    ax.set_title('Frequency of Channel {}'.format(chan))
    ax.set_xlabel('Frequency (kHz)')
    ax.set_ylabel('Power (dB)')

fig = plt.gcf()
fig.set_size_inches(13,8)
plt.show()


(302712, 2)