__init__.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # -*- coding: utf-8 -*-
  2. import numpy as np
  3. import pyaudio
  4. import sys
  5. class MicCapture(object):
  6. BUFFER_SIZE = 2048
  7. CHANNELS = 1
  8. FORMAT = pyaudio.paInt16
  9. METHOD = "default"
  10. SAMPLE_RATE = 44100
  11. HOP_SIZE = BUFFER_SIZE//2
  12. PERIOD_SIZE_IN_FRAME = HOP_SIZE
  13. maxValue = 2**16
  14. bar_count = 35
  15. LastResult = {
  16. "min":0,
  17. "max":0,
  18. "avg":0,
  19. "bars":0,
  20. "bars_string": ""
  21. }
  22. def __init__(self):
  23. self.pA = pyaudio.PyAudio()
  24. def Update(self):
  25. self.LastResult = self.GetVolume(15)
  26. def GetVolume(self, duration):
  27. p=pyaudio.PyAudio()
  28. CHUNK = 4096
  29. #stream=p.open(format=self.FORMAT,channels=self.CHANNELS,rate=self.SAMPLE_RATE,input=True, frames_per_buffer=CHUNK)
  30. stream=p.open(format=self.FORMAT,channels=self.CHANNELS,rate=self.SAMPLE_RATE,input=True, frames_per_buffer=self.BUFFER_SIZE)
  31. min = 999
  32. max = 0
  33. count = 0
  34. total = 0
  35. for i in range(int(duration*self.SAMPLE_RATE/self.BUFFER_SIZE)):
  36. #data = np.fromstring(stream.read(CHUNK),dtype=np.int16)
  37. #peak=np.average(np.abs(data))*2
  38. data = np.fromstring(stream.read(1024),dtype=np.int16)
  39. peak = np.abs(np.max(data)-np.min(data))/self.maxValue
  40. bars="#"*int(peak*self.bar_count)+" "*int(self.bar_count-peak*self.bar_count)
  41. #print("[%s]"%bars)
  42. count +=1
  43. total+=peak
  44. if peak<min:
  45. min=peak
  46. if peak>max:
  47. max=peak
  48. res = {
  49. "min": min,
  50. "max": max,
  51. "avg": total/count,
  52. "bars":int(peak*self.bar_count),
  53. "bars_string": bars
  54. }
  55. stream.stop_stream()
  56. stream.close()
  57. p.terminate()
  58. return res