国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python調用百度語音REST API

2020-02-15 22:51:21
字體:
來源:轉載
供稿:網友

本文實例為大家分享了python調用百度語音REST API的具體代碼,供大家參考,具體內容如下

(百度的rest接口的部分網址發生了一定的變化,相關代碼已更新)

百度通過 REST API 的方式給開發者提供一個通用的 HTTP 接口,基于該接口,開發者可以輕松的獲得語音合成與語音識別能力。SDK中只提供了PHP、C和JAVA的相關樣例,使用python也可以靈活的對端口進行調用,本文描述了簡單使用Python調用百度語音識別服務 REST API 的簡單樣例。

1、語音識別與語音合成的調用

注冊開發者帳號和創建應用的過程就不再贅述,百度的REST API在調用過程基本分為三步:

獲取token 向Rest接口提交數據 處理返回數據

具體代碼如下所示:

#!/usr/bin/python3import urllib.requestimport urllibimport jsonimport base64class BaiduRest:  def __init__(self, cu_id, api_key, api_secert):    # token認證的url    self.token_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"    # 語音合成的resturl    self.getvoice_url = "http://tsn.baidu.com/text2audio?tex=%s&lan=zh&cuid=%s&ctp=1&tok=%s"    # 語音識別的resturl    self.upvoice_url = 'http://vop.baidu.com/server_api'    self.cu_id = cu_id    self.getToken(api_key, api_secert)    return  def getToken(self, api_key, api_secert):    # 1.獲取token    token_url = self.token_url % (api_key,api_secert)    r_str = urllib.request.urlopen(token_url).read()    token_data = json.loads(r_str)    self.token_str = token_data['access_token']    pass  def getVoice(self, text, filename):    # 2. 向Rest接口提交數據    get_url = self.getvoice_url % (urllib.parse.quote(text), self.cu_id, self.token_str)    voice_data = urllib.request.urlopen(get_url).read()    # 3.處理返回數據    voice_fp = open(filename,'wb+')    voice_fp.write(voice_data)    voice_fp.close()    pass  def getText(self, filename):    # 2. 向Rest接口提交數據    data = {}    # 語音的一些參數    data['format'] = 'wav'    data['rate'] = 8000    data['channel'] = 1    data['cuid'] = self.cu_id    data['token'] = self.token_str    wav_fp = open(filename,'rb')    voice_data = wav_fp.read()    data['len'] = len(voice_data)    data['speech'] = base64.b64encode(voice_data).decode('utf-8')    post_data = json.dumps(data)    r_data = urllib.request.urlopen(self.upvoice_url,data=bytes(post_data,encoding="utf-8")).read()    # 3.處理返回數據    return json.loads(r_data)['result']if __name__ == "__main__":  # 我的api_key,供大家測試用,在實際工程中請換成自己申請的應用的key和secert  api_key = "SrhYKqzl3SE1URnAEuZ0FKdT"   api_secert = "hGqeCkaMPb0ELMqtRGc2VjWdmjo7T89d"  # 初始化  bdr = BaiduRest("test_python", api_key, api_secert)  # 將字符串語音合成并保存為out.mp3  bdr.getVoice("你好北京郵電大學!", "out.mp3")  # 識別test.wav語音內容并顯示  print(bdr.getText("out.wav"))            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 绍兴县| 肇庆市| 江安县| 莲花县| 慈溪市| 和田县| 衢州市| 延寿县| 东平县| 克山县| 陕西省| 长治市| 焉耆| 邻水| 无锡市| 深泽县| 广灵县| 微博| 灵山县| 肇州县| 忻城县| 井陉县| 灌阳县| 芒康县| 通道| 巧家县| 库尔勒市| 遂昌县| 浑源县| 平利县| 宜川县| 万州区| 许昌市| 建平县| 南和县| 弋阳县| 乐平市| 广宁县| 肇源县| 永平县| 阿坝县|