Spectral Analysis of Audio - DFT, Windows and Spectrogram
In questa pagina 6
Spectral (Fourier) analysis is the main application of the DFT: given a signal one wants to know which frequencies it contains and with what amplitude. In theory one would need the DTFT of over all ; in practice only a finite stretch of samples is available and only the DFT (Discrete Fourier TransformHeuristic derivation of the discrete Fourier transform for N-periodic discrete-time signals: complex exponentials with period N, the finite basis of N modes obtained from the difference equation x(k)-x(k-N)=0, orthogonality, the coefficient formula and the definition of the DFT with its periodicity and matrix form.Discrete Fourier Transform →) can be computed. The two approximations, windowing in time and sampling in frequency, produce artefacts that must be recognised: side lobes, loss of resolution, amplitude error. The reasoning is the same for images and audio; for signals whose frequency changes in time the STFT is used (last section).
1. The effect of the window
A complex exponential
Let , . Its DTFT is a periodic impulse train: . The position of the impulse gives and its area . But if only samples are observed, the observed signal is
Multiplication in time becomes periodic convolution in frequency and the impulse turns into a copy of the transform of the window:
The last equality is the sum of a geometric series of ratio . The ratio of sines is the Dirichlet kernel, a "periodic sinc".
Fact (spectrum of a sinusoid observed for samples). The peak of is at and equals ; vanishes at (). The part between the two zeros is the main lobe, of width ; the parts between successive zeros are the side lobes, of width . The first side lobe is about of the main one, i.e. , whatever is.
Example. and : peak , zeros at multiples of rad, main lobe of width rad. The maximum of the first side lobe is .
Increasing narrows the main lobe (width ) and approaches the ideal impulse, but the relative amplitude of the side lobes does not decrease.
Several components: resolution and leakage
If , by linearity : the two copies of the kernel add up and interfere. Two problems follow.
- Resolution: if and are too close, the two main lobes merge into a single peak and two lines are not recognised. Rule of thumb: two tones are separated if they are farther apart than about half the width of the main lobe, i.e. for the rectangular window. The resolution depends only on the duration of the observation and on the window, not on zero-padding.
- Leakage (spectral leakage): the energy of a tone escapes into the side lobes and can mask a weaker nearby tone, making the amplitude estimates wrong too.
To reduce interference one takes as large as possible (narrow main lobes) or changes the window.
Example (lab). with , , and : the central tone is with respect to the others. To see it the side lobes of the two strong tones must be under (with a margin, say ): neither the rectangular window () nor the Hamming window () does.
2. Sampling in frequency
Computing the -point DFT of the observed signal gives the values , : samples of the DTFT at . A tone at an arbitrary in general does not coincide with one of these points, and the samples can miss the vertex of the main lobe: the estimated amplitude is wrong.
Condition for a correct peak. With , the amplitude is read correctly only if with an integer (the tone falls on a bin). Equivalent: the window contains an integer number of periods of the tone. Then the main lobe is sampled at the vertex and all the other samples fall on the zeros: the DFT is a single line.
The reason: for the samples and coincide, so the periodic repetition of the observed stretch has no jump.
Example. , .
- (on a bin): for and for all others.
- (halfway between two bins): , and many other non-zero values (leakage). The sampled peak is instead of : a loss of (scalloping loss).
- : peak ().
Zero-padding
To sample the DTFT more densely the signal is completed with zeros and an point DFT is computed. The maximum is sampled closer to the vertex and the amplitude is better estimated. With , :
| 32 | 64 | 128 | 1024 | |
|---|---|---|---|---|
| sampled peak |
With the point is exactly a sample. Zero-padding adds no information: the samples are points of the same curve (the Dirichlet kernel), so it does not separate two tones that the window does not separate, but it allows the peak to be located better.
3. Tapered windows
The rectangular window has the narrowest main lobe (best resolution) but the highest side lobes. A tapered window falls gently to zero at the edges and has much lower side lobes, at the price of a wider main lobe: less leakage, less resolution.
Compromise (leakage versus resolution). Lower side lobes are paid with a wider main lobe; no window improves both. Several windows and lengths are tried and the spectra compared.
With a symmetric of length ():
| window | formula | main lobe width (zero to zero) | max side lobe |
|---|---|---|---|
| rectangular | |||
| triangular (Bartlett) | |||
| Hann | |||
| Hamming | (course material: ) | ||
| Blackman | (course material: ) |
Side-lobe levels depend little on ; the widths are times . Hann is a "raised cosine" at 100%; Hamming has a pedestal () that lowers the first side lobe but leaves far lobes decaying less; Blackman adds a corrective term. For the adjustable Kaiser window see Digital Filtering of Audio SignalsA causal FIR filter of order M computes y[n] = sum b_k x[n-k], a weighted moving average whose impulse response is the coefficient sequence; FIR filters are designed by truncating the Fourier series of the ideal response with a window (rectangular gives Gibbs overshoot of 9 percent and 21 dB, tapered windows lower the side lobes and widen the transition, Kaiser adjusts it), while the IIR Butterworth filter has squared modulus 1/(1+(W/W0)^(2N)) and is fixed by order N and cut-off; multirate processing changes the sampling rate by expansion (insert L-1 zeros, then low-pass with cut-off pi/L and gain L) and decimation (low-pass with cut-off pi/M, then keep one sample in M).Digital Filtering of Audio Signals →.
The transforms of cosine windows come from the Dirichlet kernel: with is a sum of three terms, and in centred form where . The side lobes of the three terms partly cancel, hence the low side lobes.
Example (lab, weak tone at ). With samples (from the design formula with , , , giving ) and a Kaiser window with , the tone at emerges at above a leakage of . With the rectangular and the Hamming window of the same length the maximum around is at and , well above the tone: it is leakage of the strong tones and the weak tone cannot be told apart.
4. Real sinusoids and two close tones
A real sinusoid is the sum of two exponentials at opposite frequencies. Everything above holds for each; it suffices to estimate the one in because the other is its mirror. With a rectangular window and a tone on a bin: , so . With a generic window the peak is and (coherent gain). Example. , , : and . With a Hann window () about would be read.
Example: two close tones. One observes samples of with a Hann window centred at . The separation is . The Hann main lobe has width , half-width :
- : , the lobes merge: a single peak, at , of height .
- : : two separate peaks, at (height ) and (height ).
If two tones are closer than the resolution, the result also depends on the relative phase with which the two lobes add: the same with another window position may give a single peak or two false humps at and . Below the resolution one cannot say whether there are one or two tones.
In practice. (1) Fix the wanted resolution and choose with about for rectangular, for Hann/Hamming, for Blackman. (2) Choose the window from the needed dynamic range: if a strong tone can hide one down, side lobes under are needed (Blackman, Kaiser). (3) Choose (a power of two, zero-padding) to read peaks better. (4) Correct the amplitude with the coherent gain and remember the loss of up to if the tone is not on a bin.
5. Short-time Fourier transform and spectrogram
The DFT gives the global spectrum of a finite signal: it says which frequencies are present but not when. An audio signal, a voice, a moving whistle have a frequency content that changes in time. Computing one enormous DFT over the whole signal would require waiting for all the samples and a huge computation, unacceptable for real-time processing. The solution is to view the long signal as the concatenation of many short signals and compute many short DFTs: the short-time Fourier transform (STFT), whose graphical representation is the spectrogram.
Definition (STFT). Let be a long sequence and an analysis window (for instance Hann), non-zero only for , with much smaller than the length of . For each analysis instant :
Two steps: windowing ( extracts the stretch of length starting at , a frame, and weights it) and a short DFT of points (zero-padded if ) giving the local spectrum. The parameter is the frequency: , i.e. . The parameter is the time; it moves in jumps of samples (hop size), with . If the frames overlap; the common choice is (50% overlap). The number of frames for a signal of length is .
Example. samples, , and : frames; for a real signal the bins ( values) suffice by conjugate symmetry. With and : frames.
Spectrogram. is a function of two variables. It is shown as an image: horizontal axis time (), vertical axis frequency ( in rad/sample, , or Hz), grey level (or colour) proportional to , to (dB scale, which also shows weak components) or to (power density). A bright horizontal line is a stable tone; an inclined line a rising or falling frequency; a vertical dash an impulse (flat spectrum). Example (lab). scipy.signal.spectrogram with a Hamming window of samples, nfft=256 and noverlap=128: , frequency resolution and for a -sample signal frames and bins.
The time-frequency trade-off
The most important choice is the window length , which acts in two opposite ways.
Frequency resolution. Each spectral line appears in the spectrogram as the main lobe of the window transform, whose width is inversely proportional to : , with depending on the window (main lobe rectangular, Hann and Hamming, Blackman). Frequencies closer than about the half-width of the lobe merge. To separate close lines a long window is needed. A window shorter than a period of the signal gives no information on its periodicity.
Time resolution. The frame sees a stretch of length : a sudden change (for instance a frequency that starts abruptly) appears blurred over an interval comparable to . To locate changes precisely a short window is needed.
Time-frequency trade-off. The window must be short to follow changes in time and long to resolve close frequencies: the two requirements are opposite and cannot be satisfied together. For an unknown signal spectrograms with different lengths are computed: what is evident in one may be hidden in another.
Example: two close tones and a transition. The test signal (length ) is for ; for ; for . STFT with a Hann window, , at three instants:
| instant | true content | ||
|---|---|---|---|
| tones at and | two peaks: () and () | a single peak at () | |
| one tone at | a peak at | a peak at (wide) | |
| tones at and | two peaks , | two peaks , (wide) |
The tones at and are apart. With the Hann half-width is , so they are resolved; with it is , so they are merged. Those at and are apart and are separated even with . For two tones at distance the condition on Hann is : with one gets .
The cost in time. At the tone at appears suddenly. Measuring the amplitude of the line at in the frames, the rise from 10% to 90% of the maximum takes samples for and for : the long window blurs the transition by about samples, the short one locates it well. A model: for a Hann window centred at , with limited to , the line has relative amplitude (the area of the window falling after the instant ); at it is . This is an example of the general principle: long window frequency resolution and time blur ; the product of the two uncertainties stays constant.
Choosing the parameters. Window : from the wanted resolution, ( for Hann/Hamming) and from the duration of the phenomena to follow ( no longer than the event). Window shape: Hann or Hamming for a good balance; rectangular only if the narrowest lobe is needed and leakage does not matter. Hop : by default; for a smoother image (more frames). : a power of two, ; zero-padding to trace peaks better (it does not change the resolution).
Typical mistakes
- Confusing zero-padding with an increase of resolution, or reading the amplitude of an off-bin tone without correction.
- Believing that a longer window lowers the side lobes of the rectangular window: it only narrows the lobes.
- Believing that zero-padding improves time or frequency resolution in the spectrogram: it only densifies the samples.
- Using a single window length for a signal with both close tones and fast transitions.
Versione ripasso
- Windowing. Observing samples is multiplying by . For : , (Dirichlet kernel).
- Lobes. Peak at . Zeros at . Main lobe width ; side lobes wide. First side lobe dB regardless of . : main lobe rad. Growing narrows the lobe but does not lower the side lobes.
- Resolution. Two tones separate if farther than about (half the main lobe). Depends on and the window, not on zero-padding.
- Leakage. Energy in the side lobes can mask a weaker nearby tone. Lab: a tone dB down is invisible with rectangular ( dB) or Hamming ( dB).
- Frequency sampling. The -point DFT samples the DTFT at . With the peak is right only if the tone falls on a bin (integer number of periods).
- Scalloping. : tone on a bin () gives ; between bins () in bins 4 and 5, loss dB; : ( dB).
- Zero-padding. , : peak for , for . Does not separate tones the window cannot, but locates the peak better.
- Tapered windows. Fall to zero at the edges: lower side lobes, wider main lobe. Compromise leakage vs resolution. (Main lobe, max side lobe): rectangular , dB; triangular , ; Hann , ; Hamming , ; Blackman , .
- Formulas. Hann ; Hamming ; Blackman ; Kaiser in Digital Filtering of Audio SignalsA causal FIR filter of order M computes y[n] = sum b_k x[n-k], a weighted moving average whose impulse response is the coefficient sequence; FIR filters are designed by truncating the Fourier series of the ideal response with a window (rectangular gives Gibbs overshoot of 9 percent and 21 dB, tapered windows lower the side lobes and widen the transition, Kaiser adjusts it), while the IIR Butterworth filter has squared modulus 1/(1+(W/W0)^(2N)) and is fixed by order N and cut-off; multirate processing changes the sampling rate by expansion (insert L-1 zeros, then low-pass with cut-off pi/L and gain L) and decimation (low-pass with cut-off pi/M, then keep one sample in M).Digital Filtering of Audio Signals →.
- Why Hann has low lobes. Three Dirichlet kernels: , ; side lobes partly cancel.
- Close tones. with Hann: separation . (): one peak at ; (): two peaks at and . Below the resolution the relative phase decides: one or two tones cannot be told.
- Real sinusoid. Rectangular, on a bin: , . Generic window: . , : ; with Hann about .
- Procedure. from the resolution ( rectangular, Hann/Hamming, Blackman, units of ); window from the dynamic range; ; correct amplitude with coherent gain (loss up to dB off-bin).
- Lab Kaiser. dB tone: , ; tone at dB above leakage dB; rectangular and Hamming leave and dB.
- STFT. , , , (usually ). . Frames for length : . , , , : 324 frames, 513 bins; , : 1241 frames.
- Spectrogram. Image with time horizontal, frequency vertical, level , or . Horizontal line = stable tone; inclined = changing frequency; vertical dash = impulse. Lab: Hamming 256,
nfft=256,noverlap=128: , 77 frames, 129 bins. - Trade-off. Lobe : long window = good frequency resolution but time blur about ; short window = good localisation but merged lines. Try several lengths.
- Test signal. for ; to ; to . At : two peaks, one peak at ; and : both resolve (wider with ).
- Transition. The tone starts at : 10%-90% rise samples () vs (). Model: relative amplitude , ; at .
- Threshold. Hann half-width ; tones apart separate with .
- Parameters. , not longer than the event; ( for smoother); power of two. Principle: frequency resolution , time blur .
- Typical mistakes: zero-padding as extra resolution; off-bin amplitude uncorrected; longer window believed to lower the rectangular side lobes.