ARTE
BELLEZA Y BIENESTAR
ARTESANÍA
CULTURA E HISTORIA
ENTRETENIMIENTO
MEDIO AMBIENTE
COMIDA Y BEBIDAS
INGENIERÍA INVERSA
CIENCIAS
DEPORTES
TECNOLOGÍA
TECNOLOGÍA VESTIBLE
Audio Spectrum Analyser: an FFT Program for the Sound Card
Ed

Creado por

Ed

4. diciembre 2026FI
0
0
0
0
0

Audio Spectrum Analyser: an FFT Program for the Sound Card

A short Python program that turns a computer's sound input into a spectrum analyser: it takes a block of samples, windows it, runs an FFT and plots the level of every frequency in dB. It reads a sine's amplitude and frequency, shows harmonics and noise, and also works on WAV files.
Principiante
30 minutes

Instrucciones

1

What the FFT reads

Cargando el cuaderno de Jupyter…
2

The program

Install Python 3 with numpy, matplotlib and sounddevice, save this as spectrum.py and run it.
spectrum.pypython
"""Audio spectrum analyser: Hann-windowed FFT of a sound card input or a WAV file.
  python3 spectrum.py                 live from the default input (needs: pip install sounddevice numpy matplotlib)
  python3 spectrum.py tone.wav        a WAV file (16-bit PCM), first N samples
Options: --n 8192 (FFT length, power of two)  --rate 48000 (live sample rate)
Amplitudes are in full-scale units (1.0 = the largest sample the input can give); a sine shows its peak amplitude."""
import sys, argparse, wave
import numpy as np
import matplotlib.pyplot as plt

def spectrum(x, rate):
    n = len(x)
    w = np.hanning(n)                                  # Hann window: 0.5 - 0.5 cos(2 pi k/(n-1))
    X = np.fft.rfft((x - x.mean()) * w)
    amp = 2 * np.abs(X) / w.sum()                      # sine peak amplitude, corrected for the window's gain
    f = np.arange(len(X)) * rate / n                   # bin k sits at k * rate / n
    return f, amp

def read_wav(path, n):
    with wave.open(path) as wf:
        if wf.getsampwidth() != 2: sys.exit("16-bit PCM WAV only")
        rate, ch = wf.getframerate(), wf.getnchannels()
        data = np.frombuffer(wf.readframes(n), dtype="<i2").astype(float) / 32768
        return data[::ch][:n], rate                     # first channel

def main():
    ap = argparse.ArgumentParser(); ap.add_argument("wav", nargs="?"); ap.add_argument("--n", type=int, default=8192)
    ap.add_argument("--rate", type=int, default=48000); ap.add_argument("--png")
    a = ap.parse_args()
    if a.n & (a.n - 1): sys.exit("--n must be a power of two")
    if a.wav:
        x, rate = read_wav(a.wav, a.n)
        if len(x) < a.n: sys.exit(f"file has only {len(x)} samples")
    else:
        import sounddevice as sd
        rate = a.rate
        x = sd.rec(a.n, samplerate=rate, channels=1, dtype="float32", blocking=True)[:, 0].astype(float)
    f, amp = spectrum(x, rate)
    k = int(np.argmax(amp[1:]) + 1)
    print(f"bin width {rate / a.n:.2f} Hz; strongest peak {f[k]:.1f} Hz at {amp[k]:.4f} full scale "
          f"({20 * np.log10(amp[k]):.1f} dBFS)")
    plt.figure(figsize=(10, 5)); plt.semilogx(f[1:], 20 * np.log10(amp[1:] + 1e-12))
    plt.xlabel("Frequency (Hz)"); plt.ylabel("Amplitude (dBFS)"); plt.ylim(-140, 5); plt.grid(True, which="both", alpha=0.3)
    plt.title(f"Spectrum, {a.n} points at {rate} Hz")
    plt.savefig(a.png) if a.png else plt.show()

if __name__ == "__main__":
    main()

Herramientas necesarias:

Ordenador de sobremesaOrdenador de sobremesa
3

Measure a signal

Feed the signal into the line input with an audio cable and run python3 spectrum.py: it prints the bin width and the strongest peak and plots the spectrum. If the peak reads near 0 dBFS the input is clipping: turn the signal down. A clean sine shows one peak; harmonics show at 2x, 3x its frequency. The sound card only sees up to half its sample rate, 24 kHz at 48 kHz.

Herramientas necesarias:

Ordenador de sobremesaOrdenador de sobremesa
Cable de audioCable de audio

Herramientas requeridas

2

CC0 Dominio público

Este Plano se publica bajo CC0. Eres libre de copiar, modificar, distribuir y usar este trabajo para cualquier propósito, sin pedir permiso.

Apoya al Maker comprando productos a través de su Plano, donde gana una Comisión del Maker establecida por los vendedores, o crea una nueva iteración de este Plano e inclúyela como conexión en tu propio Plano para compartir ingresos.

Discusión

(0)

Iniciar sesión para unirte a la discusión

Cargando comentarios...