前言
语音合成技术能将用户输入的文字,转换成流畅自然的语音输出,并且可以支持语速、音调、音量设置,打破传统文字式人机交互的方式,让人机沟通更自然。
应用场景
将游戏场景中的公告、任务或派单信息通过语音播报,让玩家玩游戏或配送员送货的同时,也可接听新任务。
文学小说类软件,可以利用百度语音合成技术将文学小说作品进行高质量的朗读,流畅清晰,解放双眼,畅听世界。
软件架构
Python3.7.2、Django2.1.7、baidu-aip(百度语音API)
案例
这里只展示部分代码,有兴趣的同学可以自行下载源码安装调试。
import os import time import codecs from aip import AipSpeech from django.shortcuts import render from django.http import HttpResponse ''' pip install --upgrade pip pip install django pip install baidu-aip ''' def main(request): return render(request, 'index.html') def m_main(request): return render(request, 'm_index.html') def convert(request): message = request.POST.get("message") switch = request.POST.get("switch") mp3 = du_say(message, switch) return HttpResponse(mp3) def du_say(message, switch): write_txt(message) app_id = '*****' api_key = '*****' secret_key = '*****' cl<mark>本文来源gaodaimacom搞#^代%!码&网(</mark>ient = AipSpeech(app_id, api_key, secret_key) if switch == "true": switch = 3 else: switch = 4 result = client.synthesis(message, 'zh', 1, { 'vol': 5, 'per': switch, }) t = time.time() now_time = lambda: int(round(t * 1000)) path = os.getcwd() + os.path.sep + "static" + os.path.sep + "audio"+os.path.sep audio = path+str(now_time())+'.mp3' # 识别正确返回语音二进制 错误则返回dict 参照下面错误码 if not isinstance(result, dict): with open(audio, 'wb') as f: f.write(result) return str(now_time())+'.mp3' def write_txt(message): t = time.time() now_time = lambda: int(round(t * 1000)) path = os.getcwd() + os.path.sep + "static" + os.path.sep + "text"+os.path.sep text = path+str(now_time())+'.txt' with codecs.open(text, 'a', encoding='utf8')as f: f.write(message)
本地部署
从码云拉取项目到本地:
https://gitee.com/52itstyle/baidu-speech.git
配置百度语音API:
# 自行注册申请 https://console.bce.baidu.com/ai/#/ai/speech/app/list
启动项目:
# 切换到项目根目录,执行 manage.py runserver
外网部署
这里以Linux为例,代理使用 openresty。
安装 Python3
wget https://www.python.org/ftp/python/3.7.1/Python-3.7.1.tar.xz
事先安装依赖,否则后期安装会报错:
yum -y install zlib* yum -y install libffi-devel
下面开始正式安装:
# 解压 tar -xvf Python-3.7.1.tar.xz # 切换大目录 cd Python-3.7.1 # 配置编译 ./configure # 编译安装 make && make install