فن
خوبصورتی اور تندرستی
دستکاری
ثقافت اور تاریخ
تفریح
ماحول
خوراک اور مشروبات
ریورس انجینئرنگ
سائنسز
کھیل
ٹیکنالوجی
پہننے والے آلات
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)

لاگ ان بحث میں شامل ہونے کے لیے

تبصرے لوڈ ہو رہے ہیں...