WsParamSynthesizeObject.py 4.1 KB

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