# -*- coding: utf-8 -*- import numpy as np import pyaudio import sys class MicCapture(object): BUFFER_SIZE = 2048 CHANNELS = 1 FORMAT = pyaudio.paInt16 METHOD = "default" SAMPLE_RATE = 44100 HOP_SIZE = BUFFER_SIZE//2 PERIOD_SIZE_IN_FRAME = HOP_SIZE maxValue = 2**16 bar_count = 35 LastResult = { "min":0, "max":0, "avg":0, "bars":0, "bars_string": "" } def __init__(self): self.pA = pyaudio.PyAudio() def Update(self): self.LastResult = self.GetVolume(15) def GetVolume(self, duration): p=pyaudio.PyAudio() CHUNK = 4096 #stream=p.open(format=self.FORMAT,channels=self.CHANNELS,rate=self.SAMPLE_RATE,input=True, frames_per_buffer=CHUNK) stream=p.open(format=self.FORMAT,channels=self.CHANNELS,rate=self.SAMPLE_RATE,input=True, frames_per_buffer=self.BUFFER_SIZE) min = 999 max = 0 count = 0 total = 0 for i in range(int(duration*self.SAMPLE_RATE/self.BUFFER_SIZE)): #data = np.fromstring(stream.read(CHUNK),dtype=np.int16) #peak=np.average(np.abs(data))*2 data = np.fromstring(stream.read(1024),dtype=np.int16) peak = np.abs(np.max(data)-np.min(data))/self.maxValue bars="#"*int(peak*self.bar_count)+" "*int(self.bar_count-peak*self.bar_count) #print("[%s]"%bars) count +=1 total+=peak if peakmax: max=peak res = { "min": min, "max": max, "avg": total/count, "bars":int(peak*self.bar_count), "bars_string": bars } stream.stop_stream() stream.close() p.terminate() return res