import numpy as np
import numpy.linalg as la
import matplotlib.pyplot as pt
from simple_audio import play
Let's fix some parameters. The sample_rate
says how many values (so-called "samples") are played per second.
The audio hardware takes these 'samples' in blocks of 1024, so we need to do some rounding.
sample_rate = 44100
count = (sample_rate//1024) * 1024
t = np.linspace(0, 1, sample_rate)[:count]
Here are some example tones. What are they?
#signal = np.sin(440*2*np.pi*t)
#signal = np.sin(880*2*np.pi*t)
#signal = 0.5 * (np.sin(880*2*np.pi*t) + np.sin(440*2*np.pi*t))
signal = 0.5 * (np.sin(1209*2*np.pi*t) + np.sin(697*2*np.pi*t))
play(signal)
pt.plot(signal[:500])
That last tone--wouldn't it be useful to pick that apart into its frequency components?
n = 2047
assert n % 2 == 1
cos_k = np.arange(0, n//2 + 1, dtype=np.float64)
sin_k = np.arange(1, n//2 + 1, dtype=np.float64)
x = np.linspace(0, 2*np.pi, n, endpoint=False)
DFT = np.zeros((n,n))
DFT[:, ::2] = np.cos(cos_k*x[:, np.newaxis])
DFT[:, 1::2] = np.sin(sin_k*x[:, np.newaxis])
IDFT = la.inv(DFT)
pt.xlim([-100, 1100])
pt.plot(np.abs(IDFT.dot(signal[:n])))