65 lines
1.6 KiB
Python
65 lines
1.6 KiB
Python
import soundbox
|
||
import numpy as np
|
||
import matplotlib
|
||
import matplotlib.pyplot as plt
|
||
import sys
|
||
|
||
if len(sys.argv) != 3:
|
||
print(f"""Utilisation: {sys.argv[0]} [source] [output]
|
||
|
||
Affiche la transformée de Fourier du fichier [source] sur un graphe
|
||
dans le fichier [output]. Passer - comme [output] fait s’afficher le
|
||
graphe dans une fenêtre.""")
|
||
sys.exit(1)
|
||
|
||
source_file = sys.argv[1]
|
||
output_file = sys.argv[2]
|
||
|
||
# Calcul du FFT
|
||
signal = soundbox.load_signal(source_file)
|
||
vecs = np.fft.fft(signal)[:soundbox.samp_rate // 2]
|
||
values = np.absolute(vecs) / np.max(np.absolute(vecs))
|
||
|
||
# Génération du graphe
|
||
plt.style.use('ggplot')
|
||
plt.rcParams.update({
|
||
'figure.figsize': (10, 5),
|
||
'font.size': 16,
|
||
'font.family': 'Concourse T4',
|
||
})
|
||
|
||
fig, ax = plt.subplots()
|
||
ax.tick_params(axis='both', which='major', labelsize=12)
|
||
|
||
freq_filter = values >= 0.01
|
||
freq = np.arange(len(values))
|
||
ax.plot(freq[freq_filter], values[freq_filter])
|
||
|
||
# Configuration des axes
|
||
freq_scale = soundbox.samp_rate / len(signal)
|
||
|
||
|
||
def freq_format(value, pos):
|
||
return f'{value * freq_scale:.0f} Hz'
|
||
|
||
|
||
def ampl_format(value, pos):
|
||
return f'{value:.1f}'
|
||
|
||
|
||
ax.set_xlabel('Fréquence', labelpad=10)
|
||
ax.set_xscale('log', base=2)
|
||
ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(freq_format))
|
||
ax.xaxis.set_major_locator(plt.MultipleLocator(100 / freq_scale))
|
||
|
||
ax.set_ylabel('Amplitude relative', labelpad=10)
|
||
ax.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(ampl_format))
|
||
ax.yaxis.set_major_locator(plt.MultipleLocator(.2))
|
||
|
||
# Rendu du résultat
|
||
if output_file == '-':
|
||
plt.show()
|
||
else:
|
||
plt.tight_layout()
|
||
plt.savefig(output_file)
|