毕业设计-树莓派人脸检测语音交互机器人设计(四)-------------基于百度的语音识别和语音合成、图灵机器人

经过pyaduio录音的wav文件,用百度的语音识别翻译成文字。
在百度智能云官网上注册:https://ai.baidu.com/tech/speech
注册登录后的界面。
在这里插入图片描述
创建应用就能得到相应的api接口了。
在这里插入图片描述
https://ai.baidu.com/sdk#asr下载语音识别和合成的SDK。
在这里插入图片描述
下载完成之后用发ftp协议或者samba共享到树莓派上。
解压包:unzip aip-python-sdk-2.0.0.zip
安装SDK包: sudo pip install baidu-aip

----------------准备工作已经完成,该亮代码了--------------------------

import requests
import base64  #百度语音要求对本地语音二进制数据进行base64编码
from aip import AipSpeech
base_url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s"
APP_ID = '************'
API_KEY = 'KbmcncX*******BUxdEaW'
SECRET_KEY = 'O29nOr9i******DGF25ziAKQP'
HOST = base_url % (API_KEY, SECRET_KEY)
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
def getToken(host):
    res = requests.post(host)
    return res.json()['access_token']

TOKEN = getToken(HOST)

def speech2text(file,dev_pid=1537):
    with open(file, 'rb') as f:
        speech_data = f.read()
    FORMAT = 'wav'
    RATE = '16000'
    CHANNEL = 1
    CUID = '********'
    SPEECH = base64.b64encode(speech_data).decode('utf-8')
    data = {
        'format': FORMAT,
        'rate': RATE,
        'channel': CHANNEL,
        'cuid': CUID,
        'len': len(speech_data),
        'speech': SPEECH,
        'token': TOKEN,
        'dev_pid':dev_pid
    }
    url = 'https://vop.baidu.com/server_api'
    headers = {'Content-Type': 'application/json'}
    print('正在识别...')
    r = requests.post(url, json=data, headers=headers)
    Result = r.json()
    if 'result' in Result:
        return Result['result'][0]
    else:
        return "语音识别出现错误"
    


def change_to_mp3(content='请输入要转换的文字内容,这是默认测试内容',turn=1,mp3_name='17k'):
    result  = client.synthesis(content, 'zh', 1, {
        'vol': 5,'per':0
    })
    # 识别正确返回语音二进制 错误则返回dict 参照下面错误码
    if not isinstance(result, dict):
        with open('auido.mp3', 'wb') as f:
            f.write(result)


上面APP_ID、API_KEY、SECRET_KEY填自己在百度智能云申请的api信息。
把以上的代码保存成一个py文件,在别人py文件调用speech2text()函数就能把语音识别成文字,调用change_to_mp3()就能把文字合成语音。

例子:
我把上面的代码保存为yuyin.py文件。

import yuyin
result = yuyin.speech2text('speech.wav',1537) #语音识别
print("语音识别结果:",result)
yuyin.change_to_mp3("你好啊!百度云。")  #语音合成
os.system("mplayer auido.mp3")	#播放声音

图灵机器人

官方网站:http://www.turingapi.com/
进去注册登录,创建机器人,选择相应的功能完成创建,进去之后就能获得api了。要实名验证=
在这里插入图片描述
在这里插入图片描述
准备工作就完成了,代码如下:

import json
import urllib.request 
api_url = "http://openapi.tuling123.com/openapi/api/v2"
def tring(text_input):
    req = {
        "perception":
        {
            "inputText":
            {
               "text": text_input
           },
 
           "selfInfo":
            {
               "location":
                {
                   "city": "广州",
                    "province": "广州",
                    "street": "白云区"
                }
           }
        },
 
        "userInfo": 
        {
            "apiKey": "9779cb51d3e*******d19047f8d8e4d",
            "userId": "OnlyUseAlphabet"
        }
    }
# 将字典格式的req编码为utf8
    req = json.dumps(req).encode('utf8') 
    http_post = urllib.request.Request(api_url, data=req, headers={'content-type': 'application/json'})
    response = urllib.request.urlopen(http_post)
    response_str = response.read().decode('utf8')
    response_dic = json.loads(response_str)
 
    intent_code = response_dic['intent']['code']
    results_text = response_dic['results'][0]['values']['text']
    print('图灵机器人回答:'+results_text)
    return results_text

在上面代码的apiKey填写自己的信息,保存成turing.py文件,然后在别的py文件可以通过如下调用。

import turing
turing_result=turing.tring(result)  #图灵机器人智能回答
print("图灵回答结果:",turing_result)

将上面的连起来就是,录音–>语音识别---->图灵机器人对话---->语音合成----->语音播放。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值