record.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import pyaudio
  2. from collections import deque
  3. from array import array
  4. import numpy as np
  5. import requests
  6. import json
  7. import itertools
  8. from config.config import Config
  9. # fs = 16000
  10. # seconds = 1
  11. SERVER_URL = Config["server_url"]
  12. INFERENCE_STR = Config["inference_path"]
  13. TEST_STR = Config["test_path"]
  14. class DequeEncoder(json.JSONEncoder):
  15. def default(self, obj):
  16. if isinstance(obj, deque):
  17. return list(obj)
  18. return json.JSONEncoder.default(self, obj)
  19. class Record(object):
  20. fs = 16000
  21. seconds = 1
  22. stride = fs * seconds
  23. cnt = 0
  24. def __init__(self):
  25. self.cumul_audio = deque([], maxlen = self.fs * 5)
  26. self.stream = pyaudio.PyAudio().open(format=pyaudio.paInt16, channels=1, rate=self.fs, input=True, output=True, frames_per_buffer=self.stride)
  27. def unit_test(self, output_func):
  28. self.cnt += 1
  29. output_func(str(self.cnt))
  30. def record_unit(self, output_func):
  31. snd_raw = self.stream.read(self.stride, exception_on_overflow=False)
  32. snd_data = array('h', snd_raw)
  33. audio = np.float32(snd_data)/32000
  34. audio = audio.tolist()
  35. self.cumul_audio.extend(audio)
  36. payload = {
  37. "device":"0005",
  38. "time":"seconds",
  39. "recording":{
  40. "filename":"output.mp3",
  41. "content_type":"audio/mp3",
  42. "content": list(self.cumul_audio)
  43. }
  44. }
  45. headers = {'Content-Type': 'application/json; charset=utf-8'}
  46. r = requests.post(SERVER_URL + INFERENCE_STR, data=json.dumps(payload), headers=headers)
  47. resJson = r.json()
  48. print('resJson = ', resJson)
  49. output_func(resJson['output'])
  50. def recording(output):
  51. while True:
  52. snd_raw = stream.read(stride, exception_on_overflow= False)
  53. snd_data = array('h', snd_raw)
  54. audio = np.float32(snd_data)/32000
  55. audio = audio.tolist()
  56. cumul_audio.extend(audio)
  57. payload = {
  58. "device":"0005",
  59. "time":"seconds",
  60. "recording":{
  61. "filename":"output.mp3",
  62. "content_type":"audio/mp3",
  63. "content": cumul_audio
  64. }
  65. }
  66. headers = {'Content-Type': 'application/json; charset=utf-8'}
  67. r = requests.post(SERVER_URL + TEST_STR, data=json.dumps(payload), headers=headers)
  68. # print('success recording !! ', list(itertools.islice(cumul_audio, 0, 10)))
  69. def record_chunk():
  70. snd_raw = stream.read(stride, exception_on_overflow= False)
  71. snd_data = array('h', snd_raw)
  72. audio = np.float32(snd_data)/32000
  73. audio = audio.tolist()
  74. cumul_audio.extend(audio)
  75. return list(itertools.islice(cumul_audio, 0, 10))