产品销售型的网站,门户网站建设情况汇报,黑龙江纪检监察网,用花生棒做网站快吗目前手边的一些工作#xff0c;需要实现声音播放功能#xff0c;而且仅支持wav声音格式。
现在#xff0c;一些网站上支持文字转语音功能#xff0c;但是生成的都是MP3文件#xff0c;这样还需要额外的软件来转成wav文件#xff0c;十分麻烦。
后来#xff0c;研究Pytho…目前手边的一些工作需要实现声音播放功能而且仅支持wav声音格式。
现在一些网站上支持文字转语音功能但是生成的都是MP3文件这样还需要额外的软件来转成wav文件十分麻烦。
后来研究Python发现Python可以很容易的实现上面的功能。
步骤如下
1。使用百度语音实现TTSText To Speech生成mp3文件;
2。 使用pydub和ffmpeg实现mp3转wav格式。
下面先上简单的示例代码然后对代码作简单的分析。
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
from aip import AipSpeech
from pydub import AudioSegment
# Step 1, Using baidu AI to generate mp3 file from text
#input your APP_ID/API_KEY/SECRET_KEY
APP_ID Your_APP_ID
API_KEY Your_API_KEY
SECRET_KEY Your_Secret_Key
client AipSpeech(APP_ID, API_KEY, SECRET_KEY)
result client.synthesis(你好百度, good morning, zh, 1, { vol: 5,per:4 })
if not isinstance(result, dict):
with open(test.mp3, wb) as f:
f.write(result)
# Step 2, convert the mp3 file to wav file
sound AudioSegment.from_mp3(test.mp3)
sound.export(test.wav, formatwav)
运行上面的python代码就会生成test.mp3和test.wav使用命令“aplay test.wav”可以测试播放声音。
下面对代码做解析
1。在运行之前需要安装下面的库
1.1 安装百度AI模块安装命令“pip install baidu-aip”
1.2 安装pydubpydub是python的一个音频处理库处理能对wav格式的音频直接进行处理安装命令“pip install pydub”
1.3 安装ffmpeg可以实现对mp3格式的处理安装命令“sudo apt-get install ffmpeg”
2。需要注册百度的应用开发者账户
大家可以对上述代码进行进一步的优化以实现自己想要的功能。
下面是完整的Python代码大家可以拿来使用
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-module: baiduVoiceGenerate
platform: Linux
description: Generate Speech from Text, and convert the audio to wav file.
Precondition: Please install below module before run this progrom,
1. pip install baidu-aip
2. pip install pydub
3. sudo apt-get install ffmpeg
creater: Guangwei Jiang
create time: 2018-11-21from aip import AipSpeech
from pydub import AudioSegment
import time
#input your own APP_ID/API_KEY/SECRET_KEY
APP_ID 14891501
API_KEY EIm2iXtvDSplvR5cyHU8dAeM
SECRET_KEY 4KkGGzTq2GVrBEYPLXXWEEIoyLL1F6Zt
print(baiduVoiceGenerate: V1.0, by Guanagwei_Jiang, 20181121)
str raw_input(请输入要转成语音的文字 )
client AipSpeech(APP_ID, API_KEY, SECRET_KEY)
result client.synthesis(str, zh, 1, { vol: 5,per:4 })
if not isinstance(result, dict):
with open(temp.mp3, wb) as f:
f.write(result)
sound AudioSegment.from_mp3(temp.mp3)
sound.export(time.strftime(%Y%m%d_%H%M%S, time.localtime()).wav, formatwav)
以上这篇使用Python实现文字转语音并生成wav文件的例子就是小编分享给大家的全部内容了希望能给大家一个参考也希望大家多多支持我们。
时间 2019-08-07