calculating FFT in frames and writing to a file

烂漫一生 提交于 2021-01-01 13:52:45

问题


I'm new to python,I'm trying get a FFT value of a uploaded wav file and return the FFT of each frame in each line of a text file (using GCP)

using scipy or librosa

Frame rate i require is 30fps

wave file will be of 48k sample rate

so my questions are

  1. how do i divide the samples for the whole wav file into samples of each frame
  2. How do add empty samples to make the length of the frame samples power of 2 (as 48000/30 = 1600 add 448 empty samples to make it 2048)
  3. how do i normalize the resulting FFT array to [-1,1]?

回答1:


You can use pyaudio with callback to acheive whatever you are doing.

import pyaudio
import wave
import time
import struct
import sys
import numpy as np

if len(sys.argv) < 2:
   print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
   sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

# instantiate PyAudio (1)
p = pyaudio.PyAudio()

def callback_test(data, frame_count, time_info, status):
    frame_count =1024
    elm = wf.readframes(frame_count) # read n frames
    da_i = np.frombuffer(elm, dtype='<i2') # convert to little endian int pairs
    da_fft = np.fft.rfft(da_i) # fast fourier transform for real values

    da_ifft = np.fft.irfft(da_fft)  # inverse fast fourier transform for real values 
    da_i = da_ifft.astype('<i2') # convert to little endian int pairs
    da_m = da_i.tobytes() # convert to bytes 
    return (da_m, pyaudio.paContinue)

# open stream using callback (3)
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),# sampling frequency
                output=True,
                stream_callback=callback_test)

# # start the stream (4)
stream.start_stream()

# # wait for stream to finish (5)
while stream.is_active():
    time.sleep(0.1)

# # stop stream (6)
stream.stop_stream()
stream.close()
wf.close()

# close PyAudio (7)
p.terminate()

Please refer these links for further study:

https://people.csail.mit.edu/hubert/pyaudio/docs/#example-callback-mode-audio-i-o and Python change pitch of wav file



来源:https://stackoverflow.com/questions/61301504/calculating-fft-in-frames-and-writing-to-a-file

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