ARTE
BELLEZZA E BENESSERE
MESTIERE
CULTURA E STORIA
DIVERTIMENTO
AMBIENTE
CIBO E BEVANDE
INGEGNERIA INVERSA
SCIENZE
SPORT
TECNOLOGIA
INDOSSABILI
Audio Spectrum Analyser: an FFT Program for the Sound Card
Ed

Creato da

Ed

4. dicembre 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

Istruzioni

1

What the FFT reads

Caricamento del notebook 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()

Strumenti necessari:

Computer da tavoloComputer da tavolo
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.

Strumenti necessari:

Computer da tavoloComputer da tavolo
Cavo audioCavo audio

Strumenti richiesti

2

CC0 Pubblico dominio

Questo progetto è rilasciato sotto CC0. Sei libero di copiare, modificare, distribuire e utilizzare quest'opera per qualsiasi scopo, senza chiedere permesso.

Supporta il Maker acquistando prodotti tramite il suo progetto dove guadagna una Commissione Maker stabilita dai venditori, oppure crea una nuova iterazione di questo progetto e includilo come collegamento nel tuo progetto per condividere i ricavi.

Commenti

(0)

Accedi per partecipare alla discussione

Caricamento commenti...