test_sr.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. print("{}: session start".format(self.__id))
  40. r = sr.start(aformat="pcm", ex={"hello":123})
  41. self.__slices = zip(*(iter(self.__data),) * 640)
  42. for i in self.__slices:
  43. sr.send_audio(bytes(i))
  44. time.sleep(0.01)
  45. r = sr.stop()
  46. print("{}: sr stopped:{}".format(self.__id, r))
  47. time.sleep(1)
  48. def multiruntest(num=500):
  49. for i in range(0, num):
  50. name = 'thread' + str(i)
  51. t = TestSr(name, 'tests/test1.pcm')
  52. t.start()
  53. nls.enableTrace(True)
  54. multiruntest(1)