Spectrogram

Spectrogram

BeginnerSignal Processing

Educational content in the form of a scientific draft that needs expert review before being adopted as an academic reference. No experimental result that was not actually run is shown here.

Definition

A visual representation of the value $|STFT|^2$ as a function of time and frequency, usually displayed on a decibel scale. It shows how frequency energy is distributed over time, and it is used to read sounds visually.

Mathematical Idea

We compute the STFT, then the power $P[m,k]=|X[m,k]|^2$, then convert it to decibels $10\log_{10}(P/P_{ref})$ to compress the large dynamic range. The horizontal axis is time, the vertical axis is frequency, and the color is energy. A steady tone is a horizontal line, a chirp is a slope, and a periodic harmonic sound is parallel lines (harmonics).

How It Works

  1. We compute the STFT of the signal.
  2. We take the squared magnitude of each cell to obtain power.
  3. We convert to decibels with a reference (such as the maximum value).
  4. We clip the dynamic range (e.g., 80 dB).
  5. We draw the image with a colormap.

Stages Diagram

  1. Signal
  2. STFT
  3. |·|²
  4. dB
  5. Colormap

Equations

$$P[m,k]=|X[m,k]|^2$$

The power of the cell at frame $m$ and bin $k$.

$$S_{dB}[m,k]=10\log_{10}\frac{P[m,k]}{P_{ref}}$$

Conversion to decibels relative to a reference $P_{ref}$.

Advantages

  • A quick visual reading of spectral content.
  • Harmonics and formants are visible.
  • A common input for CNN models.

Limitations

  • Phase is discarded.
  • The appearance is affected by the choice of window and its length.
  • Does not follow the perception of the ear (see the mel scale).

Use Cases

  • Studying phonetics and visually diagnosing noise.
  • Preparing inputs for classification models.
  • Teaching the concepts of time and frequency.

Applied Example

A 1000 Hz tone at $f_s=16000$ and $N=512$: the bin is $1000/(16000/512)=32$, which is what the code prints.

Code Example

PythonImplemented and Tested
import numpy as np, librosa
sr = 16000
t = np.arange(sr)/sr
x = np.sin(2*np.pi*1000*t)
S = np.abs(librosa.stft(x, n_fft=512, hop_length=128))**2
S_db = librosa.power_to_db(S, ref=np.max)    # dB relative to the maximum value
print(S_db.shape, S_db.max(), round(S_db.min(), 1))
peak_bin = S.mean(axis=1).argmax()
print("peak bin:", peak_bin, "->", peak_bin*sr/512, "Hz")

References

  1. McFee, Raffel, Liang, Ellis, McVicar, Battenberg, et al.. librosa: Audio and Music Signal Analysis in Python. Proceedings of the 14th Python in Science Conference (2015). DOI

Audio processing in the experiments takes place inside your browser. Audio, texts, and conversations are not saved on the server. Privacy Policy