WsParamSynthesizeObject.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import websocket
  2. import datetime
  3. import hashlib
  4. import base64
  5. import hmac
  6. import json
  7. from urllib.parse import urlencode
  8. import ssl
  9. from wsgiref.handlers import format_date_time
  10. from datetime import datetime
  11. from time import mktime
  12. import threading
  13. """
  14. 调用讯飞模型 文字转语音
  15. """
  16. class WsParamSynthesize:
  17. def __init__(self, APPID, APIKey, APISecret, Text, AudioName="demo"):
  18. self.APPID = APPID
  19. self.APIKey = APIKey
  20. self.APISecret = APISecret
  21. self.Text = Text
  22. self.AudioType = "mp3"
  23. self.AudioName = AudioName
  24. # 初始化其他需要的属性
  25. self.CommonArgs = {"app_id": self.APPID}
  26. if self.AudioType == "mp3":
  27. self.BusinessArgs = {"aue": "lame", "auf": "audio/L16;rate=8000", "vcn": "xiaoyan", "tte": "utf8",
  28. "sfl": 1}
  29. else:
  30. self.BusinessArgs = {"aue": "raw", "auf": "audio/L16;rate=8000", "vcn": "xiaoyan", "tte": "utf8"}
  31. self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-8')), "UTF8")}
  32. def create_url(self):
  33. url = 'wss://tts-api.xfyun.cn/v2/tts'
  34. # 生成RFC1123格式的时间戳
  35. now = datetime.now()
  36. date = format_date_time(mktime(now.timetuple()))
  37. # 拼接字符串
  38. signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"
  39. signature_origin += "date: " + date + "\n"
  40. signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"
  41. # 进行hmac-sha256进行加密
  42. signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
  43. digestmod=hashlib.sha256).digest()
  44. signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')
  45. authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
  46. self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
  47. authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
  48. # 将请求的鉴权参数组合为字典
  49. v = {
  50. "authorization": authorization,
  51. "date": date,
  52. "host": "ws-api.xfyun.cn"
  53. }
  54. # 拼接鉴权参数,生成url
  55. url = url + '?' + urlencode(v)
  56. return url
  57. def on_message(self, ws, message):
  58. try:
  59. message = json.loads(message)
  60. code = message["code"]
  61. sid = message["sid"]
  62. audio = message["data"]["audio"]
  63. if code != 0:
  64. errMsg = message["message"]
  65. print(f"Error: {errMsg}, code: {code}")
  66. return None
  67. audio = base64.b64decode(audio)
  68. status = message["data"]["status"]
  69. if status == 2:
  70. print("WebSocket is closed")
  71. ws.close()
  72. if code != 0:
  73. errMsg = message["message"]
  74. print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
  75. else:
  76. with open(f'static/demo_files/{self.AudioName}.{self.AudioType}', 'ab') as f:
  77. f.write(audio)
  78. except Exception as e:
  79. print("Exception while parsing message:", e)
  80. return None
  81. # on_error和on_close方法类似地修改,可以访问类实例的属性
  82. def on_error(self, error):
  83. print("### error:", error)
  84. # 收到websocket关闭的处理
  85. def on_close(self):
  86. print("### closed ###")
  87. def on_open(self, ws):
  88. def run(*args):
  89. d = {"common": self.CommonArgs, "business": self.BusinessArgs, "data": self.Data}
  90. d = json.dumps(d)
  91. ws.send(d)
  92. threading.Thread(target=run).start()
  93. def start(self):
  94. websocket.enableTrace(False)
  95. self.ws = websocket.WebSocketApp(self.create_url(),
  96. on_message=lambda ws, msg: self.on_message(ws, msg),
  97. on_error=lambda msg: self.on_error(msg),
  98. on_close=self.on_close,
  99. on_open=lambda ws: self.on_open(ws)) # 使用 lambda 来确保 ws 参数传递
  100. self.ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})