Generare Grafica Forma d'Onda con Python: Codice e Visualizzazione
Creare una grafica forma d'onda richiede due passaggi: genera o carica dati audio → plotta ampiezza vs. tempo. Lo stack scientifico di Python rende questo scriptabile e batchabile.
Script Completo Riproducibile
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
from scipy.signal import sawtooth, square
# 1. GENERA O CARICA AUDIO
# Opzione A: Sintetizza (seno, quadra, dente di sega, rumore)
sr = 44100 # Sample rate
duration = 2.0 # Secondi
freq = 440.0 # Hz (A4)
t = np.linspace(0, duration, int(sr * duration), endpoint=False)
# Scegli forma d'onda
waveform = np.sin(2 * np.pi * freq * t) * 0.8 # Seno
# waveform = square(2 * np.pi * freq * t) * 0.8 # Quadra
# waveform = sawtooth(2 * np.pi * freq * t) * 0.8 # Dente di sega
# Aggiungi realismo: rumore + normalizza
waveform += np.random.normal(0, 0.05, len(waveform))
waveform = waveform / np.max(np.abs(waveform))
# Opzione B: Carica file reale (decommenta)
# sr, waveform = wavfile.read("input.wav")
# if waveform.dtype != np.float32:
# waveform = waveform.astype(np.float32) / np.iinfo(waveform.dtype).max
# 2. PLOTTA FORMA D'ONDA
plt.figure(figsize=(12, 3), dpi=150)
plt.plot(t, waveform, linewidth=0.5, color='#0066cc')
plt.axis('off') # Pulito: niente assi, etichette, margini
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. OPZIONALE: SALVA AUDIO
# wavfile.write("output.wav", sr, (waveform * 32767).astype(np.int16))
Manopole di Personalizzazione
| Parametro | Effetto |
|---|---|
figsize=(W, H) | Rapporto d'aspetto. Largo/corto = forma d'onda tradizionale |
linewidth | Spessore. 0.3–1.0 tipico |
color | Esadecimale/RGB. Usa alpha per strati sovrapposti |
transparent=True | Sfondo alfa per compositing |
plt.axis('off') | Rimuove tutto il cromo |
Avanzato: Multi-Canale / Spettrogramma / Envelope RMS
# Stereo: plotta L/R separatamente o combinato
plt.plot(t, waveform[:,0], label='L', alpha=0.7)
plt.plot(t, waveform[:,1], label='R', alpha=0.7)
# Spettrogramma (frequenza vs tempo)
plt.specgram(waveform, Fs=sr, NFFT=1024, noverlap=512, cmap='inferno')
# Envelope RMS (contorno intensità)
frame_len = int(0.01 * sr) # frame 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')
Automazione Batch
import glob
for wav_file in glob.glob("*.wav"):
sr, wav = wavfile.read(wav_file)
# ... codice plot ...
plt.savefig(f"{wav_file[:-4]}_waveform.png")
plt.close()
Installa Dipendenze
pip install numpy matplotlib scipy # Per I/O audio: pip install soundfile (sostituisce scipy.io.wavfile per più formati)
Alternative Non-Python
- FFmpeg + FFprobe:
ffmpeg -i in.wav -filter_complex "showwavespic=s=1920x1080:colors=0x0066CC" out.png(singolo comando, niente Python) - Node.js:
wavesurfer.js+puppeteer(render Chrome headless) - Shader/GPU:
Shadertoy/TouchDesigner/Resolumeper tempo reale
L'approccio Python ti dà controllo programmativo completo — integra in pipeline, parametrizza per caratteristiche audio, genera migliaia di asset consistenti.