一.准備
1.百度ai開放平台提供了優質的接口資源https://ai.baidu.com/ (基本免費)
2.在語音識別的接口中, 對中文來說, 訊飛的接口是很好的選擇https://www.xfyun.cn/ (收費)
3.圖靈機器人提供了可以用http訪問的接口, http://www.turingapi.com/
二.創建
1.百度: 在具體功能中創建應用, 點擊技術文檔-> python sdk 按照文檔使用
2.圖靈機器人, 如果所示,創建機器人
在設置中可以對機器人的屬性設置,包括年齡星座等, 之后可以點擊查看api使用文檔進行使用
三.使用
由於百度的語音識別需要的格式為.pcm, 而示例中主要用win系統自帶的錄音機文件進行聲音采集,需要對文件轉碼.所以需要安裝ffmpeg, 安裝后將目錄/bin配置進系統環境變量
配置完環境變量之后,編譯器(pycharm)要重啟一下,重新加載一下環境變量,否則會報錯
如圖,環境變量配置成功, cd命令切換到音頻文件目錄下, 使用下面的命令將文件轉換為pcm格式
ffmpeg -y -i audio.wav -acodec pcm_s16le -f s16le -ac 1 -ar 16000 audio.pcm
# 1.你說一句話 # 2.根據語音轉化為文字 # 3.機器人通過對文字的處理返回應答 # 4.將應答文字轉化為語音,實現對話 import os import requests from aip import AipNlp, AipSpeech """ 你的 APPID AK SK """ APP_ID = '輸入 app_id' API_KEY = '輸入api_key' SECRET_KEY = '輸入secret_key' client = AipNlp(APP_ID, API_KEY, SECRET_KEY) client2 = AipSpeech(APP_ID, API_KEY, SECRET_KEY) client3 = AipSpeech(APP_ID, API_KEY, SECRET_KEY) # 1. 說-> 轉換為文字 # 讀取文件 def get_file_content(filePath): os.system(f'ffmpeg -y -i {filePath} -acodec pcm_s16le -f s16le -ac 1 -ar 16000 {filePath}.pcm') with open(f'{filePath}.pcm', 'rb') as fp: return fp.read() # 調用圖靈機器人交互 def to_url(text, uid): url = 'http://openapi.tuling123.com/openapi/api/v2' data = { "reqType": 0, "perception": { "inputText": { "text": "" }, }, "userInfo": { "apiKey": "圖靈機器人的apikey", "userId": "1" } } data['userInfo']['userId'] = uid data['perception']['inputText']['text'] = text
# 使用requests模塊模擬http請求 res = requests.post(url, json=data).json() return res.get('results')[-1].get('values').get('text') # 將語音轉化為文字 def text(file): # 識別本地文件 ret = client2.asr(get_file_content(file), 'pcm', 16000, { 'dev_pid': 1536, }) text = ret.get('result')[-1] return text # 將交互結果轉化為語音 def to_audio(text): result = client3.synthesis(text, 'zh', 1, { 'vol': 5, # 音量 'spd': 5, # 語速 'pit': 8, # 音調 'per': 4, # 發聲人選擇 }) # 識別正確返回語音二進制 錯誤則返回dict 參照下面錯誤碼 if not isinstance(result, dict): with open('auido.mp3', 'wb') as f: f.write(result) # 在win系統下 os.system可以直接打開這個文件 os.system('auido.mp3')
# ####入口#### t = text('錄音.m4a') # 錄音文件 放在這里
# NLP自然語言處理 ret = client.simnet('你爸爸是誰', t) print(ret) # {'log_id': 7122976772040456976, 'texts': {'text_2': '你把我是誰', 'text_1': '你爸爸是誰'}, 'score': 0.656308} # 0.656308 score = ret.get('score') print(score) # 0.656308 if score >= 0.58: # score在0.58以上證明兩個文本表達的意思基本一致 to_audio('當然是羅伯特X了') else: to_audio(t)

import os from aip import AipSpeech,AipNlp """ 你的 APPID AK SK """ APP_ID = '16027154' API_KEY = '5a8u0aLf2SxRGRMX3jbZ2VH0adfa' SECRET_KEY = 'UAaqS13z6DjD9Qbjd065dAh0HjbqPrzVadfad' client = AipSpeech(APP_ID, API_KEY, SECRET_KEY) client_nlp = AipNlp(APP_ID, API_KEY, SECRET_KEY) # res = client_nlp.simnet("你叫什么名字","你的名字是什么") # print(res) def text2audio(text): result = client.synthesis(text, 'zh', 1, { "spd": 4, 'vol': 5, "pit": 8, "per": 4 }) # 識別正確返回語音二進制 錯誤則返回dict 參照下面錯誤碼 if not isinstance(result, dict): with open('audio.mp3', 'wb') as f: f.write(result) return 'audio.mp3' def audio2text(filepath): res = client.asr(get_file_content(filepath), 'pcm', 16000, { 'dev_pid': 1536, }) print(res.get("result")[0]) return res.get("result")[0] def get_file_content(filePath): os.system(f"ffmpeg -y -i {filePath} -acodec pcm_s16le -f s16le -ac 1 -ar 16000 {filePath}.pcm") with open(f"{filePath}.pcm", 'rb') as fp: return fp.read() def goto_tl(text,uid): URL = "http://openapi.tuling123.com/openapi/api/v2" import requests data = { "perception": { "inputText": { "text": "你叫什么名字" } }, "userInfo": { "apiKey": "be41cf8596a24aec95b0e86be895cfa9asd", "userId": "123" } } data["perception"]["inputText"]["text"] = text data["userInfo"]["userId"] = uid res = requests.post(URL, json=data) # print(res.content) # print(res.text) print(res.json()) return res.json().get("results")[0].get("values").get("text") text = audio2text("jttqhbc.m4a") # 自然語言處理 簡單實現 score = client_nlp.simnet("你叫什么名字",text).get("score") print(score) if score >= 0.58: filename = text2audio("需要回復的音頻文件名") # os.system(f"ffplay {filename}") os.system(filename) answer = goto_tl(text,"qiaoxiaoqiang") filename = text2audio(answer) os.system(filename)