import numpy as npimport matplotlib.pyplot as pltimport matplotlib as mplimport pandas as pdimport aifcfrom pandas.plotting import register_matplotlib_convertersregister_matplotlib_converters() # datetime converter for a matplotlibimport seaborn as snssns.set(style="ticks", font_scale=1.5)import plotly.io as piopio.renderers.default ="plotly_mimetype+notebook_connected"import plotly.express as pximport plotly.graph_objects as gofrom plotly.subplots import make_subplotspio.templates.default ="presentation"import mathimport scipyfrom scipy.io import wavfile# %matplotlib widget
define useful functions
def open_aiff(filename): data = aifc.open(filename) Nframes = data.getnframes() str_signal = data.readframes(Nframes)# d = np.fromstring(str_signal, numpy.short).byteswap() d = np.frombuffer(str_signal, dtype=np.int16).byteswap()# if there are two channels, take only one of themif data.getnchannels() ==2: d = d[::2] N =len(d) dt =1.0/ data.getframerate() time = np.arange(N) * dtreturn time, ddef open_wav_return_fft(filename, max_freq=None): sample_rate, signal = wavfile.read(filename) time = np.arange(len(signal)) / sample_rate dt = time[1] - time[0] N =len(time) signal = normalize(signal) fft = scipy.fft.fft(signal) / N k = scipy.fft.fftfreq(N, dt) fft_abs = np.abs(fft)if max_freq ==None: max_freq = k.max() dk =1/ (time.max() - time.min()) n =int(max_freq/dk)return k[:n], fft_abs[:n]def normalize(signal):return (signal - signal.mean()) / signal.std()def fft_abs(signal, time, max_freq=None): dt = time[1] - time[0] N =len(time) fft = scipy.fft.fft(signal) / N k = scipy.fft.fftfreq(N, dt) fft_abs = np.abs(fft)if max_freq ==None: max_freq = k.max() dk =1/ (time.max() - time.min()) n =int(max_freq/dk)return k[:n], fft_abs[:n]