>> Tecnologia Eletrônica >  >> Áudio Pessoal >> Reprodutores MiniDisc

Gerar Gráficos de Forma de Onda de Som com Python: Código e Visualização

Criar gráfico de forma de onda requer duas etapas: gerar ou carregar dados de áudio → plotar amplitude vs. tempo. Stack científica do Python torna isso scriptável e batchável.

Script Completo Reproduzível

import numpy as np
import matplotlib.pyplot as plt
from scipy.io import wavfile
from scipy.signal import sawtooth, square

# 1. GERAR OU CARREGAR ÁUDIO
# Opção A: Sintetizar (seno, quadrada, serra, ruído)
sr = 44100  # Sample rate
duration = 2.0  # Segundos
freq = 440.0  # Hz (A4)
t = np.linspace(0, duration, int(sr * duration), endpoint=False)

# Escolha waveform
waveform = np.sin(2 * np.pi * freq * t) * 0.8  # Seno
# waveform = square(2 * np.pi * freq * t) * 0.8  # Quadrada
# waveform = sawtooth(2 * np.pi * freq * t) * 0.8  # Serra

# Adicione realismo: ruído + normalize
waveform += np.random.normal(0, 0.05, len(waveform))
waveform = waveform / np.max(np.abs(waveform))

# Opção B: Carregar arquivo real (descomente)
# sr, waveform = wavfile.read("input.wav")
# if waveform.dtype != np.float32:
#     waveform = waveform.astype(np.float32) / np.iinfo(waveform.dtype).max

# 2. PLOTAR FORMA DE ONDA
plt.figure(figsize=(12, 3), dpi=150)
plt.plot(t, waveform, linewidth=0.5, color='#0066cc')
plt.axis('off')  # Limpo: sem eixos, labels, margens
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. OPCIONAL: SALVAR ÁUDIO
# wavfile.write("output.wav", sr, (waveform * 32767).astype(np.int16))

Knobs de Customização

ParâmetroEfeito
figsize=(W, H)Proporção. Wide/short = waveform tradicional
linewidthEspessura. 0.3–1.0 típico
colorHex/RGB. Use alpha para camadas sobrepostas
transparent=TrueBackground alpha para composição
plt.axis('off')Remove todo chrome

Avançado: Multi-Canal / Espectrograma / Envelope RMS


# Estéreo: plote L/R separadamente ou combinado
plt.plot(t, waveform[:,0], label='L', alpha=0.7)
plt.plot(t, waveform[:,1], label='R', alpha=0.7)

# Espectrograma (frequência vs tempo)
plt.specgram(waveform, Fs=sr, NFFT=1024, noverlap=512, cmap='inferno')

# Envelope RMS (contorno de loudness)
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')

Automação em Lote


import glob
for wav_file in glob.glob("*.wav"):
    sr, wav = wavfile.read(wav_file)
    # ... código de plot ...
    plt.savefig(f"{wav_file[:-4]}_waveform.png")
    plt.close()

Instalar Dependências

pip install numpy matplotlib scipy
# Para I/O de áudio: pip install soundfile (substitui scipy.io.wavfile para mais formatos)

Alternativas Não-Python

  • FFmpeg + FFprobe: ffmpeg -i in.wav -filter_complex "showwavespic=s=1920x1080:colors=0x0066CC" out.png (comando único, sem Python)
  • Node.js: wavesurfer.js + puppeteer (render headless Chrome)
  • Shader/GPU: Shadertoy / TouchDesigner / Resolume para tempo real

A abordagem Python dá controle programático total — integre em pipelines, parametrize por features de áudio, gere milhares de assets consistentes.