# Understand librosa.stft() with Examples – Librosa Tutorial

By | April 16, 2022

librosa.stft() can compute short-time fourier transform (STFT) of an audio. In this tutorial, we will use an example to show you how to use it.

## librosa.stft()

It is defined as:

librosa.stft(y, *, n_fft=2048, hop_length=None, win_length=None, window='hann', center=True, dtype=None, pad_mode='constant')

Here y is the audio data, it is [shape=(…, n)]. However, we usually use single-channel audio, such as (73206,)

In order to understand n_fft, hop_length and win_length, you can read this tutorial:

Understand n_fft, hop_length, win_length in Audio Processing – Librosa Tutorial

This function will return a matrix with the shape [1 + n_fft/2, t]

Here t is computed based on wave time length, hop_length and win_length.

For example:

import numpy as np
import librosa

print(audio.shape, sr)
filter_length = 2048
hop_length = 256
win_length = 1024 # doesn't need to be specified. if not specified, it's the same as filter_length
window = 'hann'
librosa_stft = librosa.stft(audio, n_fft=filter_length, hop_length=hop_length, window=window)
_magnitude = np.abs(librosa_stft)

print(librosa_stft.shape) #(1025, 286)
print(librosa_stft)
print(_magnitude)

Run this code, we will see:

(73206,) 22050
(1025, 286)
[[-1.6615133e+00+0.0000000e+00j -1.4285779e+00+0.0000000e+00j
-8.6485648e-01+0.0000000e+00j ... -1.3406944e-01+0.0000000e+00j
-1.3931742e-01+0.0000000e+00j -1.4344619e-01+0.0000000e+00j]
[-1.5652657e+00+1.1424518e-17j  3.8324890e-03-1.3300831e+00j
7.6284611e-01+4.7273464e-03j ... -4.5176218e-03-1.6389240e-02j
2.3620196e-02-4.2293421e-03j  4.3006512e-04+2.9278466e-02j]
...
[ 1.6827306e-03+3.3678291e-17j  1.9515221e-04-1.4997546e-03j
-1.0526474e-03-3.7666829e-04j ... -1.0410095e-04+3.1385716e-05j
-2.1692813e-05-1.2355961e-04j -1.2302611e-04+2.2089213e-05j]
[ 4.1956102e-04+0.0000000e+00j  1.5616188e-04+0.0000000e+00j
-3.7838274e-04+0.0000000e+00j ... -2.9824604e-04+0.0000000e+00j
-6.3984242e-04+0.0000000e+00j -8.3593902e-04+0.0000000e+00j]]
[[1.6615133e+00 1.4285779e+00 8.6485648e-01 ... 1.3406944e-01
1.3931742e-01 1.4344619e-01]
[1.6113610e+00 1.3730764e+00 7.9855812e-01 ... 6.7087851e-02
6.0014624e-02 7.4979678e-02]
...
4.7145531e-04 5.0321297e-04]
[4.1956102e-04 1.5616188e-04 3.7838274e-04 ... 2.9824604e-04
6.3984242e-04 8.3593902e-04]]

Here 1000009.wav is a single-channel wav file, we will read its data using sample rate = 22050 defaultly.

Then we will get a data with shape (73206,)

n_fft = 2048, which means the stft rows = 1+ n_fft / 2 = 1 + 1024 = 1025

Because hop_length = 256, 73206 / hop_length = 73206 / 256 = 285.96, it means the t = 286.

So we will get a matrix with [1025, 286] from librosa.stft(), Elements are complex float number, such as -1.6615133e+00+0.0000000e+00j.