Skip to content

Commit

Permalink
Volume
Browse files Browse the repository at this point in the history
  • Loading branch information
aishoot authored Jan 9, 2018
1 parent 6591ce0 commit 33b0153
Show file tree
Hide file tree
Showing 3 changed files with 65 additions and 0 deletions.
27 changes: 27 additions & 0 deletions Volume/Volume.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import math
import numpy as np

# method 1: absSum
def calVolume(waveData, frameSize, overLap):
wlen = len(waveData)
step = frameSize - overLap
frameNum = int(math.ceil(wlen*1.0/step))
volume = np.zeros((frameNum,1))
for i in range(frameNum):
curFrame = waveData[np.arange(i*step,min(i*step+frameSize,wlen))]
#curFrame = curFrame - np.median(curFrame) # False
curFrame = curFrame - np.mean(curFrame) # zero-justified
volume[i] = np.sum(np.abs(curFrame))
return volume

# method 2: log10 of square sum
def calVolumeDB(waveData, frameSize, overLap):
wlen = len(waveData)
step = frameSize - overLap
frameNum = int(math.ceil(wlen*1.0/step))
volume = np.zeros((frameNum,1))
for i in range(frameNum):
curFrame = waveData[np.arange(i*step,min(i*step+frameSize,wlen))]
curFrame = curFrame - np.mean(curFrame) # zero-justified
volume[i] = 10*np.log10(np.sum(curFrame*curFrame))
return volume
Binary file added Volume/VolumeTest.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
38 changes: 38 additions & 0 deletions Volume/VolumeTest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import wave
import pylab as pl
import numpy as np
import Volume as vp

# ============ test the algorithm =============
# read wave file and get parameters.
fw = wave.open('../sounds/aeiou.wav','rb')
params = fw.getparams()
print(params)
nchannels, sampwidth, framerate, nframes = params[:4]
strData = fw.readframes(nframes)
waveData = np.fromstring(strData, dtype=np.int16)
waveData = waveData*1.0/max(abs(waveData)) # normalization
fw.close()

# calculate volume
frameSize = 256
overLap = 128
volume11 = vp.calVolume(waveData,frameSize,overLap)
volume12 = vp.calVolumeDB(waveData,frameSize,overLap)

# plot the wave
time = np.arange(0, nframes)*(1.0/framerate)
time2 = np.arange(0, len(volume11))*(frameSize-overLap)*1.0/framerate
pl.subplot(311)
pl.plot(time, waveData)
pl.ylabel("Amplitude")

pl.subplot(312)
pl.plot(time2, volume11)
pl.ylabel("absSum")

pl.subplot(313)
pl.plot(time2, volume12, c="g")
pl.ylabel("Decibel(dB)")
pl.xlabel("time (seconds)")
pl.show()

0 comments on commit 33b0153

Please sign in to comment.