#!/usr/local/bin/python # -*- coding: gbk-*- # import os,sys import time import urllib, urllib2,ssl class CBaiduTTSClass: def __init__(self,person=0,speed=5): self.cuid = "000C29447253" self.apiKey = "57IeRiLgiI1E" #百度語音申請 self.secretKey = "8b294c37938af94" self.person =str(person) self.speed=str(speed) self.get_token() self.IsSpeaking=False ## reload(sys) def get_token(self): auth_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&" auth_url = auth_url + "client_id=" + self.apiKey + "&client_secret=" + self.secretKey; ssl._create_default_https_context = ssl._create_unverified_context res = urllib2.urlopen(auth_url) resDict =eval(res.read()) ## print resDict ## print resDict['access_token'] self.token = resDict['access_token'] return True ## post audio to server def TTS(self,paramText,_delay=1): try: if not self.IsSpeaking: self.IsSpeaking=True ## self.get_token() ## text=paramText url = "http://tsn.baidu.com/text2audio?tex=" text=urllib.quote(paramText) ## text=paramText ## text=urllib.quote(paramText.decode('gbk').encode('utf-8')) url=url + text + "&lan=zh&per="+self.person+"&pit=1&spd="+self.speed+"&cuid="+self.cuid+"&ctp=1&tok="+self.token ## print 'mpg123 "%s"'%(url) ## print url ## params="http://tsn.baidu.com/text2audio?tex=" +"123"+ "&lan=zh&cuid=" + cuid +"&ctp=1&tok="+token ## os.system('mpg123 "%s"'%(url)) #mpg123 Version 1.22 os.popen('mpg123 "%s"'%(url)).read() #mpg123 Version 1.22 time.sleep(_delay) self.IsSpeaking=False return True else: print 'Speaking......' return False except TypeError: return False def PlayMp3(self,fileurl): if not self.IsSpeaking: self.IsSpeaking=True os.popen('mpg123 "%s"'%(fileurl)).read() #mpg123 Version 1.22 self.IsSpeaking=False return True else: print 'Playing......' return False def __del__(self): pass def GBK2UTF8(self,text): ## sys.setdefaultencoding( "utf-8" ) try: return urllib.quote(text.decode('gbk').encode('utf-8')) except UnicodeEncodeError: print 'UnicodeEncodeError' except TypeError: print 'TypeError' if __name__ == "__main__": ## import chardet ## print chardet.detect("8℃/12℃") mytts=CBaiduTTSClass() appellation="A," ## mytts.TTS(mytts.GBK2UTF8("心口如一,作出更好的選擇,須要覺察。當咱們沒有覺察的時候,就只能根據本身的自動化反應,沒有選擇的作出本能的應對。有覺察的時候就會選擇如何去處理。")) for line in open("Praise.txt"): print appellation+line print type(line) mytts.TTS(mytts.GBK2UTF8(appellation+line))