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 _thread as thread
  13. """
  14. 调用讯飞模型 文字转语音
  15. """
  16. class WsParamSynthesize:
  17. def __init__(self, APPID, APIKey, APISecret, Text):
  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. self.BusinessArgs = {"aue": "lame", "auf": "audio/L16;rate=16000", "vcn": "xiaoyan", "tte": "utf8", "sfl": 1}
  26. self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-8')), "UTF8")}
  27. def create_url(self):
  28. url = 'wss://tts-api.xfyun.cn/v2/tts'
  29. # 生成RFC1123格式的时间戳
  30. now = datetime.now()
  31. date = format_date_time(mktime(now.timetuple()))
  32. # 拼接字符串
  33. signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"
  34. signature_origin += "date: " + date + "\n"
  35. signature_origin += "GET " + "/v2/tts " + "HTTP/1.1"
  36. # 进行hmac-sha256进行加密
  37. signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),
  38. digestmod=hashlib.sha256).digest()
  39. signature_sha = base64.b64encode(signature_sha).decode(encoding='utf-8')
  40. authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
  41. self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
  42. authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
  43. # 将请求的鉴权参数组合为字典
  44. v = {
  45. "authorization": authorization,
  46. "date": date,
  47. "host": "ws-api.xfyun.cn"
  48. }
  49. # 拼接鉴权参数,生成url
  50. url = url + '?' + urlencode(v)
  51. # print("date: ",date)
  52. # print("v: ",v)
  53. # 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
  54. # print('websocket url :', url)
  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. thread.start_new_thread(run, ())
  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