soundbox/analyze-shorttime.py

59 lines
1.3 KiB
Python
Raw Normal View History

2020-12-17 22:08:07 +00:00
import soundbox
import numpy as np
import scipy.signal as sig
import matplotlib
import matplotlib.pyplot as plt
import sys
2020-12-17 22:08:07 +00:00
if len(sys.argv) != 3:
print(f"""Utilisation: {sys.argv[0]} [source] [output]
2020-12-17 22:08:07 +00:00
Génère le sonagramme du fichier [source] dans le fichier [output].
Passer - comme [output] fait safficher le sonagramme dans une fenêtre.""")
sys.exit(1)
source_file = sys.argv[1]
output_file = sys.argv[2]
# Calcul du STFT
signal = soundbox.load_signal(source_file)
2020-12-17 22:08:07 +00:00
freq, time, fts = sig.stft(signal, soundbox.samp_rate, nperseg=soundbox.samp_rate * 0.5)
# Génération du graphe
plt.rcParams.update({
'figure.figsize': (8, 8),
'font.size': 16,
'font.family': 'Concourse T4',
})
2020-12-17 22:08:07 +00:00
fig, ax = plt.subplots()
ax.tick_params(axis='both', which='major', labelsize=12)
2020-12-17 22:08:07 +00:00
ax.pcolormesh(
time, freq,
np.abs(fts),
cmap='plasma',
shading='gouraud')
def time_format(value, pos):
return f'{value:.0f} s'
def freq_format(value, pos):
return f'{value:.0f} Hz'
2020-12-17 22:08:07 +00:00
ax.set_xlabel('Temps')
ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(time_format))
ax.set_ylabel('Fréquence')
ax.set_ylim(0, 800)
ax.yaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(freq_format))
# Rend le résultat
if output_file == '-':
plt.show()
else:
plt.tight_layout()
plt.savefig(output_file)