没注册的话可以在官网注册一下,新人注册的话语音识别这块有赠送的使用次数
科大讯飞
cffi==1.12.3
gevent==1.4.0
greenlet==0.4.15
pycparser==2.19
six==1.12.0
websocket==0.2.1
websocket-client==0.56.0
wave
pyaudio //linux 下 播放pcm用的,转格式之类的,
//也有其他的;如果下载MP3格式的不用下载
windows 直接 pip install xxx
或 pip3 isntall xxx
linux 的话 自行下载pip 或 有python 3.6以及之后的配置一下即可.
ubuntu linux 21.04
python 3.7
#!/bin/python3
# 语音合成
import websocket
import datetime
import hashlib
import base64
import hmac
import json
from urllib.parse import urlencode
import ssl
from wsgiref.handlers import format_date_time
from datetime import datetime
from time import mktime
import _thread as thread
import os
from integrationxuF import pcm2wav
import wave
STATUS_FIRST_FRAME = 0 # 第一帧的标识
STATUS_CONTINUE_FRAME = 1 # 中间帧标识
STATUS_LAST_FRAME = 2 # 最后一帧的标识
class TTS():
"""
语音合成 TTS :Text To Speech
"""
# 初始化
def __init__(self, APPID, APIKey, APISecret, Text,OutFile,wavFile=None):
self.APPID = APPID
self.APIKey = APIKey
self.APISecret = APISecret
self.Text = Text
# 公共参数(common)
self.CommonArgs = {"app_id": self.APPID}
self.OutFile = OutFile
self.wavFile = wavFile
# 业务参数(business),更多个性化参数可在官网查看
"""
aue string => raw:未压缩的pcm lame:mp3 (当aue=lame时需传参sfl=1)
auf string => audio/L16;rate=8000:合成8K 的音频 audio/L16;rate=16000:合成16K 的音频
vcn string => 发音人,可选值:请到控制台添加试用或购买发音人,添加后即显示发音人参数值 "xiaoyan"
这里只是部分,详细的可去官网 https://www.xfyun.cn/doc/tts/online_tts/API.html#%E6%8E%A5%E5%8F%A3%E8%B0%83%E7%94%A8%E6%B5%81%E7%A8%8B
"""
self.BusinessArgs = {"aue": "lame", "sfl":1,"auf": "audio/L16;rate=16000", "vcn": "aisxping",
"tte": "utf8","auf":"audio/L16;rate=16000"}
self.Data = {"status": 2, "text": str(base64.b64encode(self.Text.encode('utf-8')), "UTF8")}
# 运行
def run(self):
websocket.enableTrace(False)
wsUrl = self.create_url()
ws = websocket.WebSocketApp(wsUrl,
on_message=self.on_message,
on_error=self.on_error,
on_close=self.on_close)
ws.on_open = self.on_open
ws.run_forever(sslopt={"cert_reqs": ssl.CERT_NONE})
# self.towav() # 这个是 请求的文件格式 是 pcm;目的是把pcm转为wav格式的;这里我用的mp3 就没必要使用这个了
print("-"*10,"运行结束","-"*10)
# pcm2wav
def towav(self):
"""
这里是分割pcm的路径,把转换为WAV格式的放到同目录下;可自行指定路径
"""
if self.wavFile is None:
splits = str(self.OutFile).split('/')
splits.pop(-1)
splits.append("demo.wav")
self.wavFile = '/'.join(splits)
# print("wavFile:",self.wavFile)
self.pcm2wav(self.OutFile,self.wavFile)
def pcm2wav(self,pcmfile,wavfile,channels=1,rate=16000):
with open(pcmfile,'rb') as fp:
pcmdata = fp.read()
with wave.open(wavfile, 'wb') as wav:
wav.setnchannels(channels)
wav.setsampwidth(16 // 8)
wav.setframerate(rate)
# 写入
wav.writeframes(pcmdata)
# 生成url
def create_url(self):
url = 'wss://tts-api.xfyun.cn/v2/tts'
# 生成RFC1123格式的时间戳
now = datetime.now()
date = format_date_time(mktime(now.timetuple()))
# 拼接字符串
signature_origin = "host: " + "ws-api.xfyun.cn" + "\n"
signature_origin += "date: " + date + "\n"
signature_origin += "GET " + "/v2/tts " + "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.b64encode(signature_sha).decode(encoding='utf-8')
authorization_origin = "api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"" % (
self.APIKey, "hmac-sha256", "host date request-line", signature_sha)
authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode(encoding='utf-8')
# 将请求的鉴权参数组合为字典
v = {
"authorization": authorization,
"date": date,
"host": "ws-api.xfyun.cn"
}
# 拼接鉴权参数,生成url
url = url + '?' + urlencode(v)
# print("date: ",date)
# print("v: ",v)
# 此处打印出建立连接时候的url,参考本demo的时候可取消上方打印的注释,比对相同参数时生成的url与自己代码生成的url是否一致
# print('websocket url :', url)
return url
def on_message(self,ws, message):
try:
message =json.loads(message)
code = message["code"]
sid = message["sid"]
audio = message["data"]["audio"]
audio = base64.b64decode(audio)
status = message["data"]["status"]
# print(message)
if status == 2:
print("ws is closed")
ws.close()
if code != 0:
errMsg = message["message"]
print("sid:%s call error:%s code is:%s" % (sid, errMsg, code))
else:
with open(self.OutFile, 'ab') as f:
f.write(audio)
except Exception as e:
print("receive msg,but parse exception:", e)
# 收到websocket错误的处理
def on_error(self,ws, error):
print("### error:", error)
# 收到websocket关闭的处理
def on_close(self,ws):
print("### closed ###")
# 收到websocket连接建立的处理
def on_open(self,ws):
def run(*args):
d = {"common": self.CommonArgs,
"business": self.BusinessArgs,
"data": self.Data,
}
d = json.dumps(d)
print("------>开始发送文本数据")
ws.send(d)
if os.path.exists(self.OutFile):
os.remove(self.OutFile)
thread.start_new_thread(run, ())
if __name__ == "__main__":
# 测试时候在此处正确填写相关信息即可运行
# 那个文本中的两个句号是为了延长一下时间,不加的话最后一个字听不清
out = os.getcwd() + '/python/demo.mp3'
# 下面这些参数 自己到官网获取即可
tts = TTS(APPID='',
APISecret='',
APIKey='',
Text="下午的一个语音合成示例。。",OutFile=out)
tts.run()