Telephone Dialing System
Designing signal and system course homework for Fourier transform applications. This notebook prepares homework materials like sound and histograms.
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
from scipy import signal
from scipy.fft import rfft, rfftfreq, irfft
import IPython
from pathlib import Path
%matplotlib inline
plt.rcParams['figure.figsize'] = (16.0, 9.0) # set default size of plots
plt.rcParams['image.interpolation'] = 'nearest'
plt.rcParams['image.cmap'] = 'gray'
def plot(time, signal, save=None, xlabel='', ylabel=''):
plt.plot(time, signal)
# plt.legend()
if ylabel:
plt.ylabel(ylabel)
if xlabel:
plt.xlabel(xlabel)
if save:
Path("imgs/").mkdir(exist_ok=True)
plt.savefig('imgs/' + save, bbox_inches='tight')
plt.show()
freq = [
(697, 1209), # 1
(770, 1477), # 6
(852, 1336), # 8
]
SOUND_D = 0.15
SILENCE_D = 0.05
x = get_time_linespace(len(freq)*(SOUND_D + SILENCE_D)+SILENCE_D)
y = np.zeros_like(get_time_linespace(SILENCE_D))
for f1, f2 in freq:
y = np.append(y, np.sin(2*np.pi*f1*get_time_linespace(SOUND_D)) + \
np.sin(2*np.pi*f2*get_time_linespace(SOUND_D)))
y = np.append(y, np.zeros_like(get_time_linespace(SILENCE_D)))
y /= np.max(np.abs(y))
print(x.shape, y.shape)
(28665,) (28665,)
plot(x, y, save='sound_sig.pdf', xlabel='Time [sec]', ylabel='Amplitude')
wavfile.write('new_data.wav', samplerate, y.astype(np.float32))
IPython.display.Audio("new_data.wav")
time_slice = np.where((0.10 <= x) & (x <= 0.12))
plot(x[time_slice], y[time_slice], 'magnified.pdf')
N = x.shape[0]
yf = rfft(y) * 2 / N
xf = rfftfreq(N, 1 / samplerate)
freq_slice = np.where(xf <= 2e3)
plot(xf[freq_slice], np.abs(yf[freq_slice]), 'ftt.pdf', xlabel='Frequency [Hz]', ylabel='Amplitude')
f, t, Sxx = signal.spectrogram(y, samplerate, window=np.ones(2048))
freq_slice = np.where(f <= 2e3)
f, Sxx = f[freq_slice], Sxx[freq_slice,:][0]
plt.pcolormesh(t, f, Sxx, shading='gouraud', cmap='jet')
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.colorbar()
plt.savefig('imgs/spec.pdf', bbox_inches='tight')
plt.show()