[Python] Reconstruct audio from cepstrum

Discussão em 'Python' iniciado por Stack, Março 29, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying a simple task > calculate the cepstrum of a small audio sample, lift it and do the inverse process to build the audio file back. I obviously made a mistake as it does not work well

    import numpy as np
    from scipy.signal import lfilter
    import soundfile as sf
    import librosa
    import IPython.display as ipd# for audio output
    import matplotlib.pyplot as plt # matplotlib is for python graphs and display

    # Define the complex cepstrum function
    def complex_cepstrum(x, nfft=None):
    if nfft is None:
    nfft = len(x)
    X = np.fft.fft(x, n=nfft)
    logX = np.log(np.abs(X))
    c = np.fft.ifft(logX, n=nfft)
    return c.real, c.imag, np.angle(X)

    # Define the liftering function
    def lifter(c_real, c_imag, lifter_order=22):
    c = c_real + 1j * c_imag
    c[0] = 0 # Set the DC component to zero
    lifter = 1 + (lifter_order / 2) * np.sin(np.pi * np.arange(len(c)) / lifter_order)
    return lifter * c.real, lifter * c.imag

    # Define the inverse complex cepstrum function
    def inverse_complex_cepstrum(c_real, c_imag, phase=None, n=None):
    if n is None:
    n = len(c_real)
    logX = c_real + 1j * c_imag
    if phase is not None:
    X = np.exp(logX + 1j * phase)
    else:
    X = np.exp(logX)
    x = np.fft.ifft(X, n=n).real
    return x

    # Load an audio sample
    x, fs = librosa.load('audio.wav', sr=44100, mono=True)

    # Pre-emphasis
    preemph = 0.97
    x = lfilter([1, -preemph], [1], x)

    # Compute the complex cepstrum
    c_real, c_imag, phase = complex_cepstrum(x)

    # Apply liftering
    c_liftered_real, c_liftered_imag = lifter(c_real, c_imag)

    # Reconstruct the audio signal
    x_reconstructed = inverse_complex_cepstrum(c_liftered_real, c_liftered_imag, phase=phase)

    # Write the reconstructed signal to a file
    sf.write('audio_rec.wav', x_reconstructed, 44100, 'PCM_24')


    I note that I have searched quite some time before reaching you here. It generates a huge amount of (white) noise on top of the audio file which I can't understand where this comes from.

    If anyone has a direction where to look, thanks a lot.

    P

    Continue reading...

Compartilhe esta Página