|
import numpy as np |
|
import scipy |
|
|
|
|
|
def spsi(msgram, fftsize, hop_length) : |
|
""" |
|
Takes a 2D spectrogram ([freqs,frames]), the fft length (= window length) and the hope size (both in units of samples). |
|
Returns an audio signal. |
|
""" |
|
|
|
numBins, numFrames = msgram.shape |
|
y_out=np.zeros(numFrames*hop_length+fftsize-hop_length) |
|
|
|
|
|
m_phase=np.zeros(numBins); |
|
m_win=scipy.signal.hanning(fftsize, sym=True) |
|
|
|
|
|
for i in range(numFrames) : |
|
m_mag=msgram[:, i] |
|
for j in range(1,numBins-1) : |
|
if(m_mag[j]>m_mag[j-1] and m_mag[j]>m_mag[j+1]) : |
|
alpha=m_mag[j-1]; |
|
beta=m_mag[j]; |
|
gamma=m_mag[j+1]; |
|
denom=alpha-2*beta+gamma; |
|
|
|
if(denom!=0) : |
|
p=0.5*(alpha-gamma)/denom; |
|
else : |
|
p=0; |
|
|
|
phaseRate=2*np.pi*(j+p)/fftsize; |
|
m_phase[j]= m_phase[j] + hop_length*phaseRate; |
|
peakPhase=m_phase[j]; |
|
|
|
|
|
if (p>0) : |
|
|
|
bin=j+1; |
|
m_phase[bin]=peakPhase+np.pi; |
|
|
|
|
|
bin=j-1; |
|
while((bin>1) and (m_mag[bin]<m_mag[bin+1])) : |
|
m_phase[bin]=peakPhase+np.pi; |
|
bin=bin-1; |
|
|
|
|
|
bin=j+2; |
|
while((bin<(numBins)) and (m_mag[bin]<m_mag[bin-1])) : |
|
m_phase[bin]=peakPhase; |
|
bin=bin+1; |
|
|
|
|
|
if(p<0) : |
|
|
|
bin=j-1; |
|
m_phase[bin]=peakPhase+np.pi; |
|
|
|
|
|
bin=j+1; |
|
while((bin<(numBins)) and (m_mag[bin]<m_mag[bin-1])) : |
|
m_phase[bin]=peakPhase+np.pi; |
|
bin=bin+1; |
|
|
|
|
|
bin=j-2; |
|
while((bin>1) and (m_mag[bin]<m_mag[bin+1])) : |
|
m_phase[bin]=peakPhase; |
|
bin=bin-1; |
|
|
|
|
|
|
|
|
|
magphase=m_mag*np.exp(1j*m_phase) |
|
magphase[0]=0; magphase[numBins-1] = 0 |
|
m_recon=np.concatenate([magphase,np.flip(np.conjugate(magphase[1:numBins-1]), 0)]) |
|
|
|
|
|
m_recon=np.real(np.fft.ifft(m_recon))*m_win |
|
y_out[i*hop_length:i*hop_length+fftsize]+=m_recon |
|
|
|
return y_out |
|
|
|
|
|
def magspect2audio(msgram, fftsize, hop_length) : |
|
return spsi(msgram, fftsize, hop_length) |
|
|
|
def logspect2audio(lsgram, fftsize, hop_length) : |
|
return spsi(np.power(10, lsgram/20), fftsize, hop_length) |
|
|
|
|
|
|
|
|
|
|
|
|
|
|