• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python Web版语音合成实例详解

python 搞代码 4年前 (2022-01-09) 27次浏览 已收录 0个评论

前言

语音合成技术能将用户输入的文字,转换成流畅自然的语音输出,并且可以支持语速、音调、音量设置,打破传统文字式人机交互的方式,让人机沟通更自然。

应用场景

将游戏场景中的公告、任务或派单信息通过语音播报,让玩家玩游戏或配送员送货的同时,也可接听新任务。

文学小说类软件,可以利用百度语音合成技术将文学小说作品进行高质量的朗读,流畅清晰,解放双眼,畅听世界。

软件架构

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

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python Web版语音合成实例详解

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址