做IFFT并保存回wavfile

2024-09-29 23:17:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的函数,我尝试在一个音频文件上做FFT,重置相位,并把它作为一个新的音频文件放在一起。首先我在两个通道上做FFT,然后对振幅进行归一化处理。当我试图做最后一个矩阵来保存音频文件时,它说:

ValueError: matrix must be 2-dimensional

即使它是二维的。我也得到了这个警告:

ComplexWarning: Casting complex values to real discards the imaginary part arr = N.array(data, dtype=dtype, copy=copy)

我不确定我处理振幅和相位的方法是否是最好的,所以我很感激能给我一些提示如何让我的代码工作。在

import scipy.fftpack as fft
from scipy.io import wavfile
import numpy as np
from scipy.signal import hanning
import math



def readNormalize(location):

    samplerate, data = wavfile.read(location)

    leftChan = data.T[0] # first track of audio
    rightChan = data.T[1]

    length = len(leftChan)
    fftLeft = fft.fft(leftChan[0:], length)
    fftRight = fft.fft(rightChan[0:], length)

    #length is half(positive frequency) of the the fft data, because other half is negative (complex conjugate)
    length = int(length/2)

    #getting the normalization value
    ownSum = 0;
    for i in range(0, length):
        ownSum += abs(fftLeft[i])
    normalizer = 1/ownSum

    amplitudesRight = []
    phasesRight = []

    phasesLeft = []
    amplitudesLeft = []

    #normalizing and setting the phases
    for i in range(0,length):
        #LEFT CHAN
        amplitudesLeft.append((abs(fftLeft[i])*normalizer))
        phasesLeft.append(0)
        #RIGHT CHAN
        amplitudesRight.append((abs(fftRight[i])*normalizer))
        phasesRight.append((math.pi/2))

        #TRIED THIS ASWELL BUT CAN'T APPEND LIKE THIS
        #fftLeft[i] = (abs(fftLeft[i])*normalizer)
        #fftLeft[i][i] = 0

        #fftRight[i] = (abs(fftRight[i])*normalizer)
        #fftRight[i][i] = math.pi/2


    #putting the phases and amps back to complex form(at least trying)
    matrixLeft = np.matrix([amplitudesLeft, phasesLeft], dtype=np.complex128)
    matrixRight = np.matrix([amplitudesRight, phasesRight], dtype=np.complex128)

    #ifft for the complex
    ifftLeft = fft.ifft(matrixLeft)
    ifftRight = fft.ifft(matrixRight)

    #putting all the data back together, 
    #doesn't work, says that matrix has to be 2-dimensional
    outputMatrix = np.matrix([ifftLeft, ifftRight],dtype=np.int16)

    wavfile.write('test.wav',samplerate, outputMatrix)

有什么想法吗?谢谢!在


Tags: theimportfftdatanpabslengthmatrix

热门问题