1
0

aliyun.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import nls
  2. import base64
  3. import threading
  4. import configure
  5. class Result:
  6. def __init__(self, text: str):
  7. self.mp3 = ""
  8. self.success = None
  9. self.txt = text
  10. self.byte = b""
  11. # 以下代码会根据上述TEXT文本反复进行语音合成
  12. class AliyunTls:
  13. class Tls:
  14. def __init__(self, url: str, key: str, secret: str, app: str, res: "Result", **kwargs):
  15. self.__res = res
  16. self.__kwargs = kwargs
  17. self.__th = threading.Thread(target=self.__run)
  18. self.url = url
  19. self.key = key
  20. self.secret = secret
  21. self.app = app
  22. def start(self):
  23. self.__th.start()
  24. self.__th.join()
  25. if self.__res.success is None:
  26. self.__res.mp3 = base64.b64encode(self.__res.byte).decode("ascii")
  27. self.__res.success = True
  28. return self.__res
  29. def on_error(self, message, *args):
  30. self.__res.success = False
  31. def on_data(self, data, *_):
  32. try:
  33. self.__res.byte += data
  34. except Exception:
  35. self.__res.success = False
  36. def __run(self):
  37. tts = nls.NlsSpeechSynthesizer(
  38. url=self.url,
  39. akid=self.key,
  40. aksecret=self.secret,
  41. appkey=self.app,
  42. on_data=self.on_data,
  43. on_error=self.on_error,
  44. )
  45. tts.start(self.__res.txt, aformat="mp3", wait_complete=True, **self.__kwargs)
  46. def __init__(self, url: str, key: str, secret: str, app: str):
  47. self.url = url
  48. self.key = key
  49. self.secret = secret
  50. self.app = app
  51. self.kwargs = {
  52. "voice": "Luca",
  53. "speech_rate": -500,
  54. }
  55. def start(self, text: str):
  56. """ 会阻塞程序进行 """
  57. return AliyunTls.Tls(self.url, self.key, self.secret, self.app, Result(text), **self.kwargs).start()
  58. if len(configure.conf["ALIYUN_KEY"]) == 0:
  59. print("Not aliyun key")
  60. exit(1)
  61. tls = AliyunTls(configure.conf["TLS_URL"], configure.conf["ALIYUN_KEY"],
  62. configure.conf["ALIYUN_SECRET"], configure.conf["TLS_APPID"])