Created
July 8, 2014 06:50
-
-
Save reyoung/e20f3c920b4b2ca28f31 to your computer and use it in GitHub Desktop.
WavToFFT Utility. Convert wave file to frequency domain.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python2 | |
""" | |
WavToFFT Utility. | |
Usage: | |
wav2fft.py <wav_file>... [ --fft_size=<fftsz> ] [ --window_size=<wsize>] [ --drop-final-frame ] [ --channel=<ch>] [--overlap=<ol>] | |
Options: | |
--fft_size=<fftsz> Size Of FFT [default: 1024]. | |
--window_size=<wsize> Size of FFT Window (in ms) [default: 25]. | |
--drop-final-frame Remove the final frame. | |
--channel=<ch> Use channel of wav [default: 0]. | |
--overlap=<ol> The windows overlap rate [default: 0.5]. | |
""" | |
__author__ = 'reyoung' | |
import os.path | |
import csv | |
from scipy.io.wavfile import read as wav_open | |
import numpy as np | |
import docopt | |
def main(filename, fft_size, wsize, dropfinalframe, ch, ol): | |
with open(filename, 'rb') as f: | |
wav_sr, wav_data = wav_open(f) | |
wsize = int(wav_sr * wsize / 1000.0) | |
wavfilename = os.path.basename(filename) | |
basename = os.path.splitext(wavfilename)[0] | |
csvfilename = os.path.dirname(filename) + '/' + basename + ".csv" | |
with open(csvfilename, 'wb') as csvf: | |
writer = csv.writer(csvf) | |
for begin in range(0, len(wav_data), int(wsize * (1-ol))): | |
end = begin + wsize | |
if end > len(wav_data): | |
end = len(wav_data) | |
if dropfinalframe: | |
break | |
wav = [w[ch] for w in wav_data[begin:end]] | |
xf = np.fft.rfft(wav, fft_size) / fft_size | |
xf = np.clip(np.abs(xf), 1e-20, 1e100) | |
writer.writerow(xf) | |
if __name__ == '__main__': | |
args = docopt.docopt(__doc__, version='wav2fft V0.1.0') | |
for fn in args['<wav_file>']: | |
main(fn, fft_size=int(args['--fft_size']), wsize=int(args['--window_size']), | |
dropfinalframe=args['--drop-final-frame'], ch=int(args['--channel']), | |
ol=float(args['--overlap'])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment