使用
scipy.fftpack我们可以将
fft内容绘制成频谱图。
这是根据我的旧帖子
下面的示例代码。
"""PlotsTime in MS Vs Amplitude in DB of a input wav signal"""import numpyimport matplotlib.pyplot as pltimport pylabfrom scipy.io import wavfilefrom scipy.fftpack import fftmyAudio = "audio.wav"#Read file and get sampling freq [ usually 44100 Hz ] and sound objectsamplingFreq, mySound = wavfile.read(myAudio)#Check if wave file is 16bit or 32 bit. 24bit is not supportedmySoundDataType = mySound.dtype#We can convert our sound array to floating point values ranging from -1 to 1 as followsmySound = mySound / (2.**15)#Check sample points and sound channel for duel channel(5060, 2) or (5060, ) for mono channelmySoundShape = mySound.shapesamplePoints = float(mySound.shape[0])#Get duration of sound filesignalDuration = mySound.shape[0] / samplingFreq#If two channels, then select only one channelmySoundoneChannel = mySound[:,0]#Plotting the tone# We can represent sound by plotting the pressure values against time axis.#Create an array of sample point in one dimensiontimeArray = numpy.arange(0, samplePoints, 1)#timeArray = timeArray / samplingFreq#Scale to milliSecondstimeArray = timeArray * 1000#Plot the toneplt.plot(timeArray, mySoundOneChannel, color='G')plt.xlabel('Time (ms)')plt.ylabel('Amplitude')plt.show()#Plot frequency content#We can get frquency from amplitude and time using FFT , Fast Fourier Transform algorithm#Get length of mySound object arraymySoundLength = len(mySound)#Take the Fourier transformation on given sample point #fftArray = fft(mySound)fftArray = fft(mySoundOneChannel)numUniquePoints = numpy.ceil((mySoundLength + 1) / 2.0)fftArray = fftArray[0:numUniquePoints]#FFT contains both magnitude and phase and given in complex numbers in real + imaginary parts (a + ib) format.#By taking absolute value , we get only real partfftArray = abs(fftArray)#Scale the fft array by length of sample points so that magnitude does not depend on#the length of the signal or on its sampling frequencyfftArray = fftArray / float(mySoundLength)#FFT has both positive and negative information. Square to get positive onlyfftArray = fftArray **2#Multiply by two (research why?)#Odd NFFT excludes Nyquist pointif mySoundLength % 2 > 0: #we've got odd number of points in fft fftArray[1:len(fftArray)] = fftArray[1:len(fftArray)] * 2else: #We've got even number of points in fft fftArray[1:len(fftArray) -1] = fftArray[1:len(fftArray) -1] * 2freqArray = numpy.arange(0, numUniquePoints, 1.0) * (samplingFreq / mySoundLength);#Plot the frequencyplt.plot(freqArray/1000, 10 * numpy.log10 (fftArray), color='B')plt.xlabel('Frequency (Khz)')plt.ylabel('Power (dB)')plt.show()#Get List of element in frequency array#print freqArray.dtype.typefreqArrayLength = len(freqArray)print "freqArrayLength =", freqArrayLengthnumpy.savetxt("freqData.txt", freqArray, fmt='%6.2f')#Print FFtarray informationprint "fftArray length =", len(fftArray)numpy.savetxt("fftData.txt", fftArray)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)