从WAV文件捕获dB级别

时间:2014-02-24 19:06:27

标签: python audio wav decibel

  

Python2。2.7.3(默认,2013年9月26日,16:35:25)[bCC 4.7.2]在linux2上   Linux Mint 14

使用Python,我正在阅读一个wav并将数据放入文本文件中。整个脚本如下。这是我的第一个Python脚本。

micsec的值可以是000000到999999之间的任何值。我经常使用lstrip('0')剥离零点。

如果值为000000,我最终得到null。我正在使用额外的步骤将null更改为0.

一步完成此操作的最佳方法是什么?

感谢您的任何意见。

!/usr/bin/python

import contextlib, datetime, math, os, time, wave, glob
from scipy.io.wavfile import read
from numpy import log10, sqrt, mean
import numpy as np

path = "/the/path/*.wav"
for fname in glob.glob(path):

print "process_wav is processing - " + fname

outfname = fname + ".txt"
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(fname))
tm=0.000000

with contextlib.closing(wave.open(fname,'r')) as f:
channels = f.getnchannels()
sampwidth = f.getsampwidth()
comptype = f.getcomptype()
frames = f.getnframes()
rate = f.getframerate()
wav_duration = frames / float(rate)
frame_duration = round((wav_duration / frames),6)

samprate, wavdata = read(fname)
chunks = np.array_split(wavdata, frames)

hdr = (
"# audio file processed - " + fname +
"\n# this file name - " + outfname +    
"\n# audio file mod time-" + str(mtime) +
"\n# channels - " + str(channels) +
"\n# sampwidth - " + str(sampwidth) +
"\n# comptype - " + str(comptype) +
"\n# frames - " + str(frames) +
"\n# rate - " + str(rate) +
"\n# wav_duration - " + str(wav_duration) +
"\n# frame_dutation - " + "{0:0.6f}".format(frame_duration) +
"\n# chunk|wave_file_name|audio_file_timestamp|chunk_second|chunk_microsecond|chunk_time_in_audio|frame_duration|dB\r\n"
)

out = open(outfname,'w')
out.write(hdr)

for i,chunk in enumerate(chunks):
try:
sec = int("{0:0.6f}".format(round(float(tm),6)).split('.')[0])
micsec = "{0:0.6f}".format(round(float(tm),6)).split('.')[1].lstrip('0')
#handle 000000 - there has to be a better way
micsec = int(float(micsec)) if len(micsec)>=1 else 0
cm = mtime + datetime.timedelta(seconds=sec,microseconds=micsec)
out.write("{}|{}|{}|{}|{}|{}|{}|{}\n".format(i, fname, mtime, sec, micsec, cm, frame_duration, 20*log10( sqrt(mean(chunk**2)))))
tm += frame_duration
except ValueError as ex:
print("value error" + str(ex))
out.write(str(i) + str(ex))
except Exception,e:
print("ERROR" + str(e))
out.write(str(i) + str(e))

out.close()

0 个答案:

没有答案