title: Capture dB levels from a WAV file
body: <blockquote>
    <p>Python 2.7.3 (default, Sep 26 2013, 16:35:25)  [GCC 4.7.2] on linux2
    Linux Mint 14</p>
  </blockquote>
  
  <p>Using Python, I am reading a wav and putting the data to a text file.  The entire script is below.  It is my first Python Script.</p>
  
  <p>The values for the micsec can be anything from 000000 to 999999.  There are frequently leading zero's which I am stripping with <code>lstrip('0')</code>.</p>
  
  <p>If the value is 000000, I end up with null.  I'm using an extra step to change null to 0.</p>
  
  <p>What is the best way to do this in a single step ?</p>
  
  <p>Thanks for any input.</p>
  
  <pre><code>!/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)&gt;=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()
  </code></pre>