ART
BEAUTY & WELLNESS
CRAFT
CULTURE & HISTORY
ENTERTAINMENT
ENVIRONMENT
FOOD & DRINKS
REVERSE ENGINEERING
SCIENCES
SPORTS
TECHNOLOGY
WEARABLES
Audio Spectrum Analyser: an FFT Program for the Sound Card
Ed

Created by

Ed

4. December 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.
Beginner
30 minutes

Instructions

1

What the FFT reads

Loading Jupyter Notebook...
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()

Tools needed:

Desktop ComputerDesktop Computer
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.

Tools needed:

Desktop ComputerDesktop Computer
Audio CableAudio Cable

Tools Required

2

CC0 Public Domain

This blueprint is released under CC0. You are free to copy, modify, distribute, and use this work for any purpose, without asking permission.

Support the Maker by purchasing products through their Blueprint where they earn a Maker Commission set by Vendors, or create a new iteration of this Blueprint and include it as a connection in your own Blueprint to share revenue.

Discussion

(0)

Log in to join the discussion

Loading comments...