linux2 Linux Mint 14 上的 Python 2.7.3(默认,2013 年 9 月 26 日,16:35:25)[GCC 4.7.2]
使用 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()