Spectrogram: compute the STFT and ISTFT#

This example shows how to compute the short-time Fourier transform (STFT) of a signal, that is, its spectrogram. It also shows how to use the inverse short-time Fourier transform (ISTFT) to get the signal corresponding to a given spectrogram.

Set up analysis#

Setting up the analysis consists of loading the required libraries, connecting to the DPF server, and retrieving the example files.

# Load Ansys libraries.
from ansys.sound.core import REFERENCE_ACOUSTIC_PRESSURE_IN_AIR
from ansys.sound.core.examples_helpers import download_flute_wav
from ansys.sound.core.server_helpers import connect_to_or_start_server
from ansys.sound.core.signal_utilities import LoadWav
from ansys.sound.core.spectrogram_processing import Istft, Stft


# Connect to a remote DPF server or start a local DPF server.
my_server, my_license_context = connect_to_or_start_server(use_license_context=True)

Load a signal#

Load a signal from a WAV file using the LoadWav class. It is returned as a list of Field.

# Return the input data of the example file.
path_flute_wav = download_flute_wav()

# Load the WAV file.
wav_loader = LoadWav(path_flute_wav)
wav_loader.process()
signal = wav_loader.get_output()[0]

# Plot the input signal.
wav_loader.plot()
flute

Compute and plot STFT#

Use the Stft class using the previously loaded signal as input.

# Set the STFT parameters to match your analysis needs.
stft = Stft(signal, fft_size=1024, window_type="HANN", window_overlap=0.5)

# Process the STFT.
stft.process()

# Plot the output.
stft.plot()
STFT, Magnitude, Phase

To display the STFT in dB SPL (that is, dB relative to 20 µPa), prefer the plot_custom() method with the proper reference value.

stft.plot_custom(
    reference_value=REFERENCE_ACOUSTIC_PRESSURE_IN_AIR,
    max_magnitude=80,
)
STFT, Magnitude, Phase

Modify the STFT parameters using the properties of the Stft class.

stft.fft_size = 4096
stft.window_overlap = 0.95
stft.window_type = "TRIANGULAR"

# Reprocess the STFT with the new parameters.
stft.process()

# Plot the modified output.
stft.plot_custom(
    reference_value=REFERENCE_ACOUSTIC_PRESSURE_IN_AIR,
    max_magnitude=80,
)
STFT, Magnitude, Phase

Compute and plot ISTFT#

Convert the STFT back to a time-domain signal using the Istft class. The required input format of the Istft class is the same as the output format of the Stft class.

spectrogram = stft.get_output()

# Instantiate the class
istft = Istft(spectrogram)

# Process the ISTFT
istft.process()

Plot the output, which is the original signal.

003 compute stft

Total running time of the script: (0 minutes 30.878 seconds)

Gallery generated by Sphinx-Gallery