22"""
33baidu voice service
44"""
5+ import json
6+ import os
57import time
68from aip import AipSpeech
79from bridge .reply import Reply , ReplyType
2123 - 1837:四川话
2224 要使用本模块, 首先到 yuyin.baidu.com 注册一个开发者账号,
2325 之后创建一个新应用, 然后在应用管理的"查看key"中获得 API Key 和 Secret Key
24- 填入 config.json 中.
25- baidu_app_id: ''
26- baidu_api_key: ''
27- baidu_secret_key: ''
28- baidu_dev_pid: '1536'
29- """
26+ 然后在 config.json 中填入这两个值, 以及 app_id, dev_pid
27+ """
3028
3129
3230class BaiduVoice (Voice ):
33- APP_ID = conf ().get ('baidu_app_id' )
34- API_KEY = conf ().get ('baidu_api_key' )
35- SECRET_KEY = conf ().get ('baidu_secret_key' )
36- DEV_ID = conf ().get ('baidu_dev_pid' )
37- client = AipSpeech (APP_ID , API_KEY , SECRET_KEY )
3831
3932 def __init__ (self ):
40- pass
33+ try :
34+ curdir = os .path .dirname (__file__ )
35+ config_path = os .path .join (curdir , "config.json" )
36+ bconf = None
37+ if not os .path .exists (config_path ): #如果没有配置文件,创建本地配置文件
38+ bconf = { "lang" : "zh" , "ctp" : 1 , "spd" : 5 ,
39+ "pit" : 5 , "vol" : 5 , "per" : 0 }
40+ with open (config_path , "w" ) as fw :
41+ json .dump (bconf , fw , indent = 4 )
42+ else :
43+ with open (config_path , "r" ) as fr :
44+ bconf = json .load (fr )
45+
46+ self .app_id = conf ().get ('baidu_app_id' )
47+ self .api_key = conf ().get ('baidu_api_key' )
48+ self .secret_key = conf ().get ('baidu_secret_key' )
49+ self .dev_id = conf ().get ('baidu_dev_pid' )
50+ self .lang = bconf ["lang" ]
51+ self .ctp = bconf ["ctp" ]
52+ self .spd = bconf ["spd" ]
53+ self .pit = bconf ["pit" ]
54+ self .vol = bconf ["vol" ]
55+ self .per = bconf ["per" ]
56+
57+ self .client = AipSpeech (self .app_id , self .api_key , self .secret_key )
58+ except Exception as e :
59+ logger .warn ("BaiduVoice init failed: %s, ignore " % e )
4160
61+
4262 def voiceToText (self , voice_file ):
4363 # 识别本地文件
4464 logger .debug ('[Baidu] voice file name={}' .format (voice_file ))
4565 pcm = get_pcm_from_wav (voice_file )
46- res = self .client .asr (pcm , "pcm" , 16000 , {"dev_pid" : self .DEV_ID })
66+ res = self .client .asr (pcm , "pcm" , 16000 , {"dev_pid" : self .dev_id })
4767 if res ["err_no" ] == 0 :
4868 logger .info ("百度语音识别到了:{}" .format (res ["result" ]))
4969 text = "" .join (res ["result" ])
@@ -57,9 +77,8 @@ def voiceToText(self, voice_file):
5777 return reply
5878
5979 def textToVoice (self , text ):
60- result = self .client .synthesis (text , 'zh' , 1 , {
61- 'spd' : 5 , 'pit' : 5 , 'vol' : 5 , 'per' : 111
62- })
80+ result = self .client .synthesis (text , self .lang , self .ctp , {
81+ 'spd' : self .spd , 'pit' : self .pit , 'vol' : self .vol , 'per' : self .per })
6382 if not isinstance (result , dict ):
6483 fileName = TmpDir ().path () + '语音回复_' + str (int (time .time ())) + '.mp3'
6584 with open (fileName , 'wb' ) as f :
0 commit comments