-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfft-graph.py
71 lines (57 loc) · 2.48 KB
/
fft-graph.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# plotting an audio file in both time-domain and frequency-domain
# oliver thurley, november 2023
# requires scipy, numpy, matplotlib libraries
# python v.3
import matplotlib.pyplot as plt
from scipy.io import wavfile
import numpy as np
###
### SET YOUR AUDIO FILE PATH HERE:
filename = "/path/to/audio.wav" #change this to your audio file
freq_limit = 8000 # Set clip upper limit (Hz) of the plots
############
def fftChart(filename):
rate, wave = wavfile.read(filename) # only works with 16-bit WAV?
# wave = wave[:, 0] #only the data from channel 0, we only want one channel # uncomment this line to convert file to mono
duration = round(len(wave) / rate, 2) # convert samples to duration in secs
t = np.arange(0.0, duration, 1/rate)
print("filename: "+ str(filename))
print("duration: "+ str(duration) + " seconds")
## PLOT CHARTS
fig, (ax, magspc, spect) = plt.subplots(nrows=3, ncols=1, sharex=False, figsize=(12, 8))
## Time-domain plot
timeSeq = np.linspace(0, duration, len(wave))
ax.plot(timeSeq, wave, color="m", linewidth=1.5)
ax.set(title=filename)
ax.set_xlabel('time (s)',fontsize=8)
ax.set_ylabel('amplitude',fontsize=8)
ax.grid(linewidth=0.2)
ax.set_yticks([]) # removes ticks
ax.tick_params(left=False, bottom=False, labelbottom=True, labelsize='smaller')
## Do spectrum plot (magnitude spectrum)
magspc.magnitude_spectrum(wave, Fs=rate, color='m')
magspc.set_xlabel('frequency (Hz)',fontsize=8)
magspc.set_ylabel('magnitude',fontsize=8)
magspc.tick_params(left=False, bottom=False)
magspc.set_yscale('linear')
magspc.grid(linewidth=0.2)
magspc.set_yticks([]) # removes ticks
magspc.tick_params(left=False, bottom=False, labelsize='smaller')
magspc.set_xlim([0, freq_limit])
magspc.grid(linewidth=0.2)
## Spectrogram plot
spect.specgram(wave, Fs=rate, NFFT=2048, cmap='magma') # NFFT= length of windowing segments
spect.set_xlabel('time (s)',fontsize=8)
spect.set_ylabel('frequency (Hz)',fontsize=8)
spect.set_ylim([0, freq_limit])
spect.tick_params(left=False, bottom=False, labelbottom=True, labelsize='smaller')
plt.subplots_adjust(hspace=0.3)
plt.savefig(filename+"-plot.png", dpi=300)
# plt.show()
## Uncomment this section for batch processing audio files in a folder:
# import os, glob
# path = 'folder/path/'
# for filename in glob.glob(os.path.join(path, '*.wav')):
# fftChart(filename)
## Run process on (single) filename:
fftChart(filename)