使用百度AIP接口,实现文本转语音(在线TTS)
1 import time 2 from aip import AipSpeech 3 from playsound import playsound
4 5 """ 你的 APPID AK SK 需要自己注册百度AI账号,建立应用来获取""" 6 APP_ID = '*********' 7 API_KEY = '********' 8 SECRET_KEY = '********' 9 command = '你好世界' 10 client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) 11 play_count = 0 12 while True: 13 for i in range(3,8):#切换语速,范围:0 - 10c 14 print('当前语速:%d' % i) 15 for j in range(0,5):#切换TTS人声,0,1,3,4 16 result = client.synthesis(command, 'zh', 1, {'vol': 5,'spd':i,'pit':5,'per':j}) 17 # 识别正确返回语音二进制 错误则返回dict 参照下面错误码 18 if not isinstance(result, dict): 19 play_count += 1 20 with open('auido.mp3', 'wb+') as f: 21 f.write(result) 22 try: 23 playsound('auido.mp3') 24 except: 25 play_count -= 1 26 print('play error ' + str(j)) 27 pass 28 else: 29 print('get result error ' + str(j)) 30 print('播放次数:%d' % play_count) 31 time.sleep(3)
===========================================================================================
这里播放使用playsound(v1.2.2),这个库有个问题:播放后不会释放资源,需要修改源码实现,具体修改方法如下:
编辑文件:playsound.py
------脱命散人[记]