目录
一、模型选择
二、流程
三、核心代码展示
一、模型选择
科大讯飞超拟人识别
二、流程
超拟⼈合成协议 | 讯飞开放平台文档中心 (xfyun.cn)
三、核心代码展示
# coding: utf-8
import _thread as thread
import os
import time
import base64import base64
import datetime
import hashlib
import hmac
import json
from urllib.parse import urlparse
import ssl
from datetime import datetime
from time import mktime
from urllib.parse import urlencode
from wsgiref.handlers import format_date_time
import websocket
import openpyxl
from concurrent.futures import ThreadPoolExecutor, as_completed
import osclass Ws_Param(object):# 初始化def __init__(self, APPID, APIKey, APISecret, gpt_url):self.APPID = APPIDself.APIKey = APIKeyself.APISecret = APISecretself.host = urlparse(gpt_url).netlocself.path = urlparse(gpt_url).pathself.gpt_url = gpt_url# 生成urldef create_url(self):# 生成RFC1123格式的时间戳now = datetime.now()date = format_date_time(mktime(now.timetuple()))# 拼接字符串signature_origin = "host: " + self.host + "\n"signature_origin += "date: " + date + "\n"signature_origin += "GET " + self.path + " HTTP/1.1"# 进行hmac-sha256进行加密signature_sha = hmac.new(self.APISecret.encode('utf-8'), signature_origin.encode('utf-8'),digestmod=hashlib.sha256).digest()signature_sha_base64 = base64.b64encode(signature_sha).decode(encoding='utf-8')authorization_origin = f'api_key="{self.APIKey}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature_sha_base64}"'authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')# 将请求的鉴权参数组合为字典v = {"authorization": authorization,"date": date,"host": self.host}# 拼接鉴权参数,生成urlurl = self.gpt_url + '?' + urlencode(v)# 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致return url# 收到websocket错误的处理
def on_error(ws, error):print("### error:", error)# 收到websocket关闭的处理
def on_close(ws):print("### closed ###")# 收到websocket连接建立的处理
def on_open(ws):thread.start_new_thread(run, (ws,))# 收到websocket消息的处理
def on_message(ws, message):message = json.loads(message)code = message['header']['code']if code != 0:print("### 请求出错: ", message)else:payload = message.get("payload")status = message['header']['status']if status == 2:print("### 合成完毕")ws.close()if payload and payload != "null":audio = payload.get("audio")if audio:audio = audio["audio"]with open(fr'./{ws.vcn}.mp3', 'ab') as f:f.write(base64.b64decode(audio))def run(ws, *args):body = {"header": {"app_id": ws.appid,"status": 0},"parameter": {"oral": {"spark_assist": 1,"oral_level": "mid"},"tts": {"vcn": ws.vcn,"speed": 50,"volume": 50,"pitch": 50,"bgs": 0,"reg": 0,"rdn": 0,"rhy": 0,"scn": 0,"version": 0,"L5SilLen": 0,"ParagraphSilLen": 0,"audio": {"encoding": "lame","sample_rate": 16000,"channels": 1,"bit_depth": 16,"frame_size": 0},"pybuf": {"encoding": "utf8","compress": "raw","format": "plain"}}},"payload": {"text": {"encoding": "utf8","compress": "raw","format": "json","status": 0,"seq": 0,"text": str(base64.b64encode(ws.text.encode('utf-8')), "UTF8")}}}ws.send(json.dumps(body))def main(appid, api_secret, api_key, url, text, vcn):wsParam = Ws_Param(appid, api_key, api_secret, url)wsUrl = wsParam.create_url()ws = websocket.WebSocketApp(wsUrl, on_message=on_message, on_error=on_error, on_close=on_close, on_open=on_open)websocket.enableTrace(False)ws.appid = appidws.text = textws.vcn = vcnws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})if __name__ == "__main__":main(appid="",api_secret="",api_key="",url="wss://cbm01.cn-huabei-1.xf-yun.com/v1/private/medd90fec",# 待合成文本text="今天天气很不错。",# 发音人参数vcn = "x4_lingyuzhao_oral")