python利用百度api自动将文字转换成语音并进行音频输出和保存
from aip import AipSpeech
from pydub import AudioSegment
from pydub.playback import play
import io
""" 你的 APPID AK SK """
APP_ID = '16007034'
API_KEY = '9cVZDkCrl0sZP3wpQlMeqZq2'
SECRET_KEY = 'lGTYdBrcomGUAgfPCt2jrYO9Rg68IMAB'
speech = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
"""----------------------------------------------
read_text函数
输入
text:需要读的文本
save:是否保存成音频
name:如果保存那保存成什么名字
输出
直接读出音频,成功返回1
----------------------------------------------"""
def read_text(text,save = 0,name ="audio"):
result = speech.synthesis(
text,
"zh",
1,)
if not isinstance(result, dict):
print('识别成功,正在播放音频')
voice = AudioSegment.from_file(io.BytesIO(result), format="mp3")
play(voice)
if save:
with open(name+'.mp3', 'wb') as f:
f.write(result)
return 1
read_text('K-D小昊',1,'audio')