How can I reverse a scipy.signal.spectrogram to audio with Python?

折月煮酒 提交于 2020-03-24 09:43:04

问题


I have:

import librosa
from scipy import signal 
import scipy.io.wavfile as sf    

samples, sample_rate = sf.read(args.file)
nperseg = int(sample_rate * 0.001 * 20)
frequencies, times, spectrogram = signal.spectrogram(samples, 
                                                     sample_rate, 
                                                     nperseg=nperseg, 
                                                     window=signal.hann(nperseg))

audio_signal = librosa.griffinlim(spectrogram)
print(audio_signal, audio_signal.shape)

sf.write('test.wav', audio_signal, sample_rate)

However, this produces a (near) empty sound file.


回答1:


As @DrSpill mentioned, scipy.io.wav.read and scipy.io.wav.read orders were wrong and also the import from librosa was not correct. This should do it:

import librosa
import numpy as np
import scipy.signal
import scipy.io.wavfile

# read file
file    = "temp/processed_file.wav"
fs, sig = scipy.io.wavfile.read(file)
nperseg = int(fs * 0.001 * 20)

# process
frequencies, times, spectrogram = scipy.signal.spectrogram(sig, 
                                                           fs, 
                                                           nperseg=nperseg, 
                                                           window=scipy.signal.hann(nperseg))
audio_signal = librosa.core.spectrum.griffinlim(spectrogram)
print(audio_signal, audio_signal.shape)

# write output
scipy.io.wavfile.write('test.wav', fs, np.array(audio_signal, dtype=np.int16))

Remark: The resulting file had an accelerated tempo when I heard it, I think this is due to your processing but with some tweaking it should work.

A good alternative, would be to only use librosa, like this:

import librosa
import numpy as np

# read file
file    = "temp/processed_file.wav"
sig, fs = librosa.core.load(file, sr=8000)

# process
abs_spectrogram = np.abs(librosa.core.spectrum.stft(sig))
audio_signal = librosa.core.spectrum.griffinlim(abs_spectrogram)

print(audio_signal, audio_signal.shape)

# write output
librosa.output.write_wav('test2.wav', audio_signal, fs)


来源:https://stackoverflow.com/questions/60377585/how-can-i-reverse-a-scipy-signal-spectrogram-to-audio-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!