.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "gallery/spectrograms/plot_stft_spectrogram.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_gallery_spectrograms_plot_stft_spectrogram.py: STFT spectrogram ================ The complex STFT as an array, its magnitude in dB, and the inverse transform. Reconstruction from the unmodified STFT returns the original signal. .. GENERATED FROM PYTHON SOURCE LINES 8-15 .. code-block:: Python import matplotlib.pyplot as plt import numpy as np import audio_samples as aus from audio_samples import spectral .. GENERATED FROM PYTHON SOURCE LINES 16-17 A rising chirp over a steady tone. .. GENERATED FROM PYTHON SOURCE LINES 17-22 .. code-block:: Python sr = 22050 chirp = aus.generation.chirp(200.0, 8000.0, 2.0, sr).as_f32() tone = aus.generation.sine_wave(1000.0, 2.0, sr, amplitude=0.3).as_f32() y = (chirp + tone).to_numpy() .. GENERATED FROM PYTHON SOURCE LINES 23-24 ``spectral.stft`` takes a NumPy array and returns a ``(bins, frames)`` array. .. GENERATED FROM PYTHON SOURCE LINES 24-33 .. code-block:: Python hop = 256 d = spectral.stft(y, n_fft=1024, hop_length=hop) db = spectral.amplitude_to_db(np.abs(d), ref="max", top_db=80.0) fig, ax = plt.subplots(figsize=(7, 3.5)) im = ax.imshow(db, origin="lower", aspect="auto", extent=[0, y.size / sr, 0, sr / 2]) ax.set(xlabel="Time (s)", ylabel="Frequency (Hz)", title="Magnitude (dB)") fig.colorbar(im, ax=ax, label="dB") .. image-sg:: /gallery/spectrograms/images/sphx_glr_plot_stft_spectrogram_001.png :alt: Magnitude (dB) :srcset: /gallery/spectrograms/images/sphx_glr_plot_stft_spectrogram_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 34-35 ``spectral.istft`` inverts it. .. GENERATED FROM PYTHON SOURCE LINES 35-39 .. code-block:: Python back = spectral.istft(d, hop_length=hop, length=y.size) error = np.max(np.abs(back - y)) print(f"largest reconstruction error: {error:.2e}") assert error < 1e-4 .. rst-class:: sphx-glr-script-out .. code-block:: none largest reconstruction error: 4.77e-07 .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.106 seconds) .. _sphx_glr_download_gallery_spectrograms_plot_stft_spectrogram.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_stft_spectrogram.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_stft_spectrogram.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_stft_spectrogram.zip `