test_sr.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import time
  2. import threading
  3. import sys
  4. import nls
  5. from tests.test_utils import (TEST_ACCESS_TOKEN, TEST_ACCESS_APPKEY)
  6. class TestSr:
  7. def __init__(self, tid, test_file):
  8. self.__th = threading.Thread(target=self.__test_run)
  9. self.__id = tid
  10. self.__test_file = test_file
  11. def loadfile(self, filename):
  12. with open(filename, 'rb') as f:
  13. self.__data = f.read()
  14. def start(self):
  15. self.loadfile(self.__test_file)
  16. self.__th.start()
  17. def test_on_start(self, message, *args):
  18. print('test_on_start:{}'.format(message))
  19. def test_on_error(self, message, *args):
  20. print('on_error args=>{}'.format(args))
  21. def test_on_close(self, *args):
  22. print('on_close: args=>{}'.format(args))
  23. def test_on_result_chg(self, message, *args):
  24. print('test_on_chg:{}'.format(message))
  25. def test_on_completed(self, message, *args):
  26. print('on_completed:args=>{} message=>{}'.format(args, message))
  27. def __test_run(self):
  28. print('thread:{} start..'.format(self.__id))
  29. sr = nls.NlsSpeechRecognizer(
  30. token=TEST_ACCESS_TOKEN,
  31. appkey=TEST_ACCESS_APPKEY,
  32. on_start=self.test_on_start,
  33. on_result_changed=self.test_on_result_chg,
  34. on_completed=self.test_on_completed,
  35. on_error=self.test_on_error,
  36. on_close=self.test_on_close,
  37. callback_args=[self.__id]
  38. )
  39. while True:
  40. print('{}: session start'.format(self.__id))
  41. r = sr.start(ex={'format':'pcm', 'hello':123})
  42. self.__slices = zip(*(iter(self.__data),) * 640)
  43. for i in self.__slices:
  44. sr.send_audio(bytes(i))
  45. time.sleep(0.01)
  46. r = sr.stop()
  47. print('{}: sr stopped:{}'.format(self.__id, r))
  48. time.sleep(5)
  49. def multiruntest(num=500):
  50. for i in range(0, num):
  51. name = 'thread' + str(i)
  52. t = TestSr(name, 'tests/test1.pcm')
  53. t.start()
  54. nls.enableTrace(True)
  55. multiruntest(1)