Stack Exchange
How to restore spectrogram to audio？
I used the following code to convert the audio to spectrogram, now I try to get the spectrogram back to audio again, but don't know how to write the code.
import os
import librosa
import numpy as np
import matplotlib.pyplot as plt
import cv2


def get_spectrogram(path):
    data, fs = librosa.load(path, sr=None, mono=True)
    spect = librosa.stft(data, n_fft=1024, hop_length=320, win_length=1024)
    return spect


def extract_features():
    i=0

    data_path = "./datasets"
    labels = ['mrdd0', 'mrso0', 'mrws0', 'mtjs0', 'mtpf0', 'mtrr0', 'mwad0', 'mwar0']
    # print("labels：", labels)

    total_data = []
    total_label = []

    for label in labels:
        label_path = data_path + "\\" + label
        # print(label_path)
        wav_names = os.listdir(label_path)
        for wav_name in wav_names:
            if wav_name.endswith(".wav"):
                wav_path = label_path + "\\" + wav_name
                # print(wav_path)
                spect = get_spectrogram(wav_path)
                spect = np.abs(spect)
                spect = cv2.resize(spect, (28, 28))
                total_data.append(spect)
                total_label.append(labels.index(label))
                plt.matshow(spect)
                plt.ylabel('Frequency')
                plt.xlabel('Time(s)')
                plt.title('Spectrogram')
                plt.savefig('./datasets/image_from_output/mySpectrogram-{}.png'.format(i))
                i=i+1

                #plt.savefig('./datasets/image/mySpectrogram.png')
                plt.close()
                plt.show()

    total_data = np.array(total_data)
    total_label = np.array(total_label)
    print(total_data.shape)
    print(total_label.shape)

if __name__ == '__main__':
    extract_features()

Any help would be appreciated.It would be better if there could be code for conversion.

Also, https://dsp.stackexchange.com/questions/3406/reconstruction-of-audio-signal-from-its-absolute-spectrogram/3410#3410

(there's several questions on the topic here, and you're required to do research on your own!)

Note that an amplitude spectrogram throws away a lot of information, which you simply might not ever be able to restore. There's simply infinitely many different signals with the same spectrogram.
