Générer Graphiques Forme d'Onde Sonore avec Python : Code & Visualisation
Créer un graphique forme d'onde nécessite deux étapes : générer ou charger données audio → tracer amplitude vs temps. La stack scientifique Python rend cela scriptable et batchable.
Script Complet Reproductible
import numpy as np import matplotlib.pyplot as plt from scipy.io import wavfile from scipy.signal import sawtooth, square # 1. GÉNÉRER OU CHARGER AUDIO # Option A: Synthétiser (sinus, carré, dent de scie, bruit) sr = 44100 # Taux échantillonnage duration = 2.0 # Secondes freq = 440.0 # Hz (La4) t = np.linspace(0, duration, int(sr * duration), endpoint=False) # Choisissez forme d'onde waveform = np.sin(2 * np.pi * freq * t) * 0.8 # Sinus # waveform = square(2 * np.pi * freq * t) * 0.8 # Carré # waveform = sawtooth(2 * np.pi * freq * t) * 0.8 # Dent de scie # Ajoutez réalisme: bruit + normalisation waveform += np.random.normal(0, 0.05, len(waveform)) waveform = waveform / np.max(np.abs(waveform)) # Option B: Charger fichier réel (décommentez) # sr, waveform = wavfile.read("input.wav") # if waveform.dtype != np.float32: # waveform = waveform.astype(np.float32) / np.iinfo(waveform.dtype).max # 2. TRACER FORME D'ONDE plt.figure(figsize=(12, 3), dpi=150) plt.plot(t, waveform, linewidth=0.5, color='#0066cc') plt.axis('off') # Propre: pas axes, labels, marges plt.subplots_adjust(left=0, right=1, top=1, bottom=0) plt.savefig("waveform.png", transparent=True, bbox_inches='tight', pad_inches=0) plt.close() # 3. OPTIONNEL: SAUVEGARDER AUDIO # wavfile.write("output.wav", sr, (waveform * 32767).astype(np.int16))
Boutons de Personnalisation
| Paramètre | Effet |
|---|---|
figsize=(W, H) | Ratio aspect. Large/court = forme d'onde traditionnelle |
linewidth | Épaisseur. 0,3–1,0 typique |
color | Hex/RGB. Utilisez alpha pour couches chevauchantes |
transparent=True | Fond alpha pour compositing |
plt.axis('off') | Supprime tout chrome |
Avancé : Multi-Canal / Spectrogramme / Enveloppe RMS
# Stéréo: tracer L/R séparément ou combiné plt.plot(t, waveform[:,0], label='L', alpha=0.7) plt.plot(t, waveform[:,1], label='R', alpha=0.7) # Spectrogramme (fréquence vs temps) plt.specgram(waveform, Fs=sr, NFFT=1024, noverlap=512, cmap='inferno') # Enveloppe RMS (contour sonorité) frame_len = int(0.01 * sr) # frames 10ms rms = np.sqrt(np.mean(waveform.reshape(-1, frame_len)**2, axis=1)) t_rms = np.linspace(0, duration, len(rms)) plt.plot(t_rms, rms, color='orange')
Automatisation par Lots
import glob for wav_file in glob.glob("*.wav"): sr, wav = wavfile.read(wav_file) # ... code tracé ... plt.savefig(f"{wav_file[:-4]}_waveform.png") plt.close()
Installer Dépendances
pip install numpy matplotlib scipy # Pour I/O audio: pip install soundfile (remplace scipy.io.wavfile pour plus formats)
Alternatives Non-Python
- FFmpeg + FFprobe :
ffmpeg -i in.wav -filter_complex "showwavespic=s=1920x1080:colors=0x0066CC" out.png(commande unique, pas Python) - Node.js :
wavesurfer.js+puppeteer(rendu Chrome headless) - Shader/GPU :
Shadertoy/TouchDesigner/Resolumepour temps-réel
L'approche Python donne contrôle programmatique total — intégrez dans pipelines, paramétrez par caractéristiques audio, générez des milliers d'assets cohérents.
