quick_fft.py 1.08 KB
Newer Older
Robozman's avatar
Robozman committed
1 2 3 4 5 6 7 8
import time
import matplotlib.pyplot as plt
import numpy as np
import scipy.io.wavfile as wavfile
import sounddevice
import time


Robozman's avatar
Robozman committed
9 10 11 12
import numpy as np

volume = 0.5     # range [0.0, 1.0]
fs = 44100       # sampling rate, Hz, must be integer
Robozman's avatar
Robozman committed
13 14
duration = 1     # in seconds, may be float
f = 1440.0       # sine frequency, Hz, may be float
Robozman's avatar
Robozman committed
15 16

# generate samples, note conversion to float32 array
Robozman's avatar
Robozman committed
17 18 19 20 21 22 23 24 25 26
samples = np.zeros( 10 * fs)
for i in range(0, 10): 
    curr_freq = 440 + (i * 1000)
    samples[(i * fs):((i + 1) * fs)] = np.sin(2*np.pi*np.arange(fs*duration)*curr_freq/fs).astype(np.float32)

plt.ion()
fig = plt.figure()
fft_plot = fig.add_subplot(111)


Robozman's avatar
Robozman committed
27

Robozman's avatar
Robozman committed
28 29 30 31 32
def plot(data):
    plt.plot(data, color='steelblue')


rate, wav_data = wavfile.read("violin.wav", mmap=True)
Robozman's avatar
Robozman committed
33
wav_data = samples
Robozman's avatar
Robozman committed
34 35 36 37 38 39 40 41
sounddevice.play(wav_data, rate)

t = time.time()
for i in range(0, 54):
    second = wav_data[i * rate:(i + 1) * rate]
    while (time.time() - t < 1):
        pass
    t = time.time()
Robozman's avatar
Robozman committed
42 43 44 45
    fft_plot.clear()
    fft_plot.plot(np.abs(np.fft.fftshift(np.fft.fft(second[:]))))
    fig.canvas.draw()
    fig.canvas.flush_events()