一、 概述
智能語音設備在生活中越來越常見,如智能手機(Cortana,Siri,Ok Google)、智能家居設備(Google Home,小米AI音箱),交互式語音應答設備(銀行,應答機),語音機器人(電話機器人、客服機器人、電銷機器人)。
衆多語音交互設備採用同樣的流程如下圖:語音識別把人發出的聲音轉換爲文字,經過自然語音處理得到意圖,再輸入數據庫獲取回答的文字,經過語音合成就能實現語音對話, 而後續這些功能可通過調用API來實現。
API(Application Programming Interface,應用程序接口)是一些預先定義的函數,或指軟件系統不同組成部分銜接的約定。目的是提供應用程序與開發人員基於某軟件或硬件得以訪問一組例程的能力,而又無需訪問原碼,或理解內部工作機制的細節。而圖靈機器人和百度人工智能平臺爲我們提供了豐富的免費接口。
二、 系統架構
流程在樹莓派上的體現是這樣的,把錄音的對話發給百度語音識別,它返回文字再發給圖靈機器人,圖靈機器人比對自己的數據庫,再返回回答的文本,把文本經過語音合成後保存到本地,然後把它播放出來,整個流程是線性流程
物件清單(BOM):
- USB攝像頭———1
- 樹莓派—————1
- 音響——————1
三、 開發流程
1.準備對應應用程序編程接口API
註冊圖靈機器人賬號和百度語音識別賬號獲取API KEY
- 百度大腦:https://ai.baidu.com/
- 圖靈機器人:http://www.turingapi.com/
2. 測試樹莓派錄音功能
採用樹莓派自帶的arecord來錄音,16000的採樣頻率,保存爲test.wav
arecord -D "plughw:1" -f S16_LE -r 16000 test.wav
其中,-D參數後接錄製設備,連接麥克風後,樹莓派上有2個設備:內部設備和外部usb設備,plughw:1代表使用外部設備。-f表示錄製的格式,-r表示聲音採樣頻率。由於後面提到的百度語音識別對音頻文件格式是有要求的,我們需要錄製成符合要求的格式。另外,在這裏我沒有指定錄製的時間,它會一直錄製下去,直到用戶按下ctrl-c。錄製後的音頻文件保存爲test.wav。
若耳機沒有聲音,則:
sudo raspi-config
找到advanced options>audio
設置成3.5mm接口
3. 調用百度語音識別的API進行語音識別
流程基本就是獲取token,把需要識別的語音信息、語音數據、token等發送給百度的語音識別服務器,就能獲取到對應的文字。
文檔見:https://ai.baidu.com/ai-doc/SPEECH/6k38lxp0r
源碼:asr.py
此部分爲百度註冊API。
client_id = "Qv4q0sKRNYLniDgUdA*****"
client_secret = "tX0SYY01H8sR3jhcl4*****"
# coding: utf-8
import urllib.request
import json
import base64
import sys
def get_access_token():
url = "https://openapi.baidu.com/oauth/2.0/token"
grant_type = "client_credentials"
client_id = "Qv4q0sKRNYLniDgUdA*****"
client_secret = "tX0SYY01H8sR3jhcl4*****"
url = url + "?" + "grant_type=" + grant_type + "&" + "client_id=" + client_id + "&" + "client_secret=" + client_secret
resp = urllib.request.urlopen(url).read()
data = json.loads(resp.decode("utf-8"))
return data["access_token"]
def baidu_asr(data, id, token):
speech_data = base64.b64encode(data).decode("utf-8")
speech_length = len(data)
post_data = {
"format" : "wav",
"rate" : 16000,
"channel" : 1,
"cuid" : id,
"token" : token,
"speech" : speech_data,
"len" : speech_length
}
url = "https://openapi.baidu.com/oauth/2.0/token"
json_data = json.dumps(post_data).encode("utf-8")
json_length = len(json_data)
#print(json_data)
req = urllib.request.Request(url, data = json_data)
req.add_header("Content-Type", "application/json")
req.add_header("Content-Length", json_length)
print("asr start request\n")
resp = urllib.request.urlopen(req)
print("asr finish request\n")
resp = resp.read()
resp_data = json.loads(resp.decode("utf-8"))
if resp_data["err_no"] == 0:
return resp_data["result"]
else:
print(resp_data)
return None
def asr_main(filename):
f = open(filename, "rb")
audio_data = f.read()
f.close()
token = get_access_token()
uuid = "1000"
resp = baidu_asr(audio_data, uuid, token)
print(resp[0])
return resp[0]
#words=asr_main("test.wav")
#print(words)
4.將百度語音識別返回的文本發送到圖靈機器人
文檔見:https://ai.baidu.com/ai-doc/SPEECH/hk38lxjye
樹莓派安裝相應庫文件:
樹莓派安裝語音識別 Python SDK,對應Python2或Python3安裝
Pip3 install baidu-aip
或
Pip install baidu-aip
通過發送Post請求獲取圖靈機器人返回的回答。
源碼:robot.py apiKey部分爲圖靈機器人註冊API。
import requests
import json
def robot_main(words):
url='http://openapi.tuling123.com/openapi/api/v2' #服務地址
params={
'reqType':0,
'perception':{
'inputText':{
'text':'' #詢問的文本
}
},
'userInfo':{
'apiKey':'ef5c5039fe804f0d974910*********', #使用你自己申請的
'userId':'ROBOT'
}
}
params['perception']['inputText']['text']=words
response=requests.post(url,json=params)
#print(response.text)
answer=json.loads(response.text)
return answer['results'][0]['values']['text']
#word_robot=robot_main('Hello')
#print(word_robot)
5. 將圖靈返回的文本發送到百度語音合成
文檔見:https://ai.baidu.com/ai-doc/SPEECH/Gk38y8lzk
源碼:tts.py 紅色部分爲百度註冊API。
from aip import AipSpeech
#""" 你的 APPID AK SK """
APP_ID = '18081**'
API_KEY = 'Qv4q0sKRNYLniDg****'
SECRET_KEY = 'tX0SYY01H8sR3jhcl4******'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
def tts_main(words):
result = client.synthesis(words, 'zh', 1, {
'vol': 5,
})
# 識別正確返回語音二進制 錯誤則返回dict 參照下面錯誤碼
if not isinstance(result, dict):
with open('auido.mp3', 'wb') as f:
f.write(result)
#tts_main('你好')
6. 集成到MAIN程序和採用腳本調用
源碼:main.py
import asr
import tts
import robot
words = asr.asr_main("test.wav")
print(words)
new_words = robot.robot_main(words)
print(new_words)
tts.tts_main(new_words)
集成到腳本中,採用樹莓派自帶的omxplayer播放合成的語音
源碼:start.sh
#! /bin/bash
arecord -D "plughw:1" -f S16_LE -r 16000 test.wav
python3 main.py
omxplayer -o local test.mp3
使用方法:
運行腳本start.sh錄音
Ctrl+C結束錄音
四、 總結
這個項目雖參考了網上一些案例,真正自己編寫的代碼量雖然不是很多,但是要求看懂官方的技術文檔,要求懂得如何結合課程所學的語音部分和Python編程能力纔可進行成功調試,但出現問題時需要有合適的排查手段,找出硬件或者軟件上的問題。通過這次項目,相信能夠獲益匪淺。而做到的語音對話還只是基礎,後期可拓展爲語音控制燈的開關,利用樹莓派強大的功能做智能家居,或者採用Qtpy5做界面,通過聲音大小實現喚醒等,實現更便捷的使用體驗等等。
– 以上,這是博主課程作業,僅此分享一下。