1 #-*-coding:utf-8-*-2 ImportSYS3 ImportRequests4 ImportJSON5 ImportMp3play6 Import Time7 8 defTalk (info):9Appkey ="e5ccc9c7c8834ec3b08940e290ff1559"Tenheaders = { One 'user-agent':'mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit' A '/537.36 (khtml, like Gecko) chrome/53.0.2785.143 Safar' - 'i/537.36', - } theURL ="http://www.tuling123.com/openapi/api?key=%s&info=%s"%(Appkey, info) -Content = Requests.get (URL, headers=headers) -Answer =json.loads (Content.text) -Baidu_api ='Http://tts.baidu.com/text2audio?idx=1&tex={0}&cuid=baidu_speech_' + 'demo&cod=2&lan=zh&ctp=1&pdt=1&spd=4&per=4&vol=5&pit=5'. Format (answer['text']) -res = Requests.get (Baidu_api, headers=headers) +With open (r'E:\python_demo\tuling.mp3','WB') as F: A f.write (res.content) at returnanswer['text'] - - defMain (info): -info = Info.decode ('gb2312'). Encode ('Utf-8') -Answer =Talk (info) -mp3 = Mp3play.load (r'E:\python_demo\tuling.mp3') in Mp3.play () -Time.sleep (min (40, Mp3.seconds ())) to mp3.stop () + Try: - Print 'tuling:%s'%Answer the exceptUnicodeencodeerror: * PrintU'I said a what yo. ' $ Panax Notoginseng if __name__=='__main__': - PrintU'start your show. ' the whileTrue: +info = raw_input ('Studog:') A ifinfo = =' the': the Break +Main (info)
Python implements a simple voice chat robot