电竞比分网-中国电竞赛事及体育赛事平台

分享

【百度語音rest API】文本轉(zhuǎn)換成語音,以及語音轉(zhuǎn)化成文本

 nxhujiee 2019-07-10

通過rest API,調(diào)用百度語音接口,將其接入智能客服。

百度語音:http://ai.baidu.com/docs/#/ASR-API/top

#!/usr/bin/python3

import urllib.request
import urllib
import json
import base64
class 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()
        r_str = str(r_str, encoding="utf-8")
        token_data = json.loads(r_str)
        self.token_str = token_data['access_token']
        pass

    def getVoice(self, text, filename):
        # 2. Rest接口提交數(shù)據(jù)
        get_url = self.getvoice_url % (urllib.parse.quote(text), self.cu_id, self.token_str)

        voice_data = urllib.request.urlopen(get_url).read()
        # 3.處理返回數(shù)據(jù)
        voice_fp = open(filename,'wb+')
        voice_fp.write(voice_data)
        voice_fp.close()
        pass

    def getText(self, filename):
        # 2. Rest接口提交數(shù)據(jù)
        data = {}
        # 語音的一些參數(shù)
        data['format'] = 'amr'
        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.處理返回數(shù)據(jù)
        r_data= str(r_data, encoding="utf-8")
        return json.loads(r_data)['result']

if __name__ == "__main__":
    # 我的api_key,供大家測試用,在實際工程中請換成自己申請的應用的keysecert
    api_key = "SrhYKqzl3SE1URnAEuZ0FKdT"
    api_secert = "hGqeCkaMPb0ELMqtRGc2VjWdmjo7T89d"
    # 初始化
    api_key='Vf9zUcTBZmZaGqGTO8uktEqs'
    api_secert='oqyXL4XmYXcyoMoUGSjbVk63Qp3oaq1X'
    bdr = BaiduRest("test", api_key, api_secert)
    # 將字符串語音合成并保存為out.mp3
    bdr.getVoice("李勤,李總,你能不能不要整天黑我了!", "out2.mp3")
    # 識別test.wav語音內(nèi)容并顯示
    print(bdr.getText("8k.amr"))

    本站是提供個人知識管理的網(wǎng)絡存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約