УРЛАГ
ГОО САЙХАН БА ЭРҮҮЛ МЭНД
ГАРААР ХИЙСЭН
СОЁЛ БА ТҮҮХ
ҮЗВЭР НААДАМ
БАЙГАЛЬ ОРЧИН
ХООЛ БА УНДАА
УРВУУ ИНЖЕНЕРЧЛЭЛ
ШИНЖЛЭХ УХААН
СПОРТ
ТЕХНОЛОГИ
ӨМСДӨГ ХЭРЭГСЭЛ
Audio Spectrum Analyser: an FFT Program for the Sound Card
Ed

Зохиогч

Ed

4. Арван хоёрдугаар сар 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.
Анхан шат
30 minutes

Зааварчилгаа

1

What the FFT reads

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()

Шаардлагатай багаж:

Ширээний компьютерШирээний компьютер
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.

Шаардлагатай багаж:

Ширээний компьютерШирээний компьютер
Аудио кабельАудио кабель

Шаардлагатай багаж

2

CC0 Нийтийн домэйн

Энэ загвар CC0 дор гаргагдсан. Та зөвшөөрөл авахгүйгээр хуулах, өөрчлөх, түгээх, ашиглах боломжтой.

Загвараар дамжуулан бүтээгдэхүүн худалдаж авч Бүтээгчийг дэмжээрэй Бүтээгчийн шимтгэл Борлуулагчаар тогтоосон, эсвэл энэ загварын шинэ хувилбар үүсгэж орлогоо хуваахын тулд өөрийн загварт холбоос болгон оруулна уу.

Хэлэлцүүлэг

(0)

Нэвтрэх хэлэлцүүлэгт нэгдэхийн тулд

Сэтгэгдлүүдийг ачаалж байна...