现在语音助手已经成为我们生活中ai的代表,下面让我们看一下语音助手的语音输入功能
进入百度开放平台后选择短语音识别
然后去领取免费的资源
创建应用
记住相关的key
本次用到的库(以及引入方法):
import speech_recognition as sr
from aip import AipSpeech
import pyttsx3
APP_ID = '27468776'
API_KEY = 'ygQgtR4DIh14lDi8gwSMCm7o'
SECRET_KEY = '7flGlZba42ZYxHudy3dSQ8YW4n89W5hc'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
try:
def rec(rate=16000):
r = sr.Recognizer()
with sr.Microphone(sample_rate=rate) as source:
print("请说话")
audio = r.listen(source)
with open("recording.wav", "wb") as f:
f.write(audio.get_wav_data())
except:
print("语音录入发生错误")
with open('recording.wav', 'rb') as f:
audio_data = f.read()
result = client.asr(audio_data, 'wav', 16000, {
'dev_pid': 1536,
})
try:
result_text = result["result"][0]
print("你说: " + result_text)
if result_text =="于金龙":
engine = pyttsx3.init()
engine.say('真帅')
engine.runAndWait()
elif result_text=="张新凯":
engine = pyttsx3.init()
engine.say('真难看')
engine.runAndWait()
except:
print("没有识别到语音")
import pyttsx3
import speech_recognition as sr
from aip import AipSpeech
# Baidu Speech API, replace with your personal key
APP_ID = '27468776'
API_KEY = 'ygQgtR4DIh14lDi8gwSMCm7o'
SECRET_KEY = '7flGlZba42ZYxHudy3dSQ8YW4n89W5hc'
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
# Use SpeechRecognition to record
try:
def rec(rate=16000):
r = sr.Recognizer()
with sr.Microphone(sample_rate=rate) as source:
print("请说话")
audio = r.listen(source)
with open("recording.wav", "wb") as f:
f.write(audio.get_wav_data())
except:
print("语音录入发生错误")
# 使用百度语音作为STT引擎
def listen():
with open('recording.wav', 'rb') as f:
audio_data = f.read()
result = client.asr(audio_data, 'wav', 16000, {
'dev_pid': 1536,
})
try:
result_text = result["result"][0]
print("你说: " + result_text)
if result_text =="阿龙":
engine = pyttsx3.init()
engine.say('真帅')
engine.runAndWait()
elif result_text=="其他人":
engine = pyttsx3.init()
engine.say('真难看')
engine.runAndWait()
except:
print("没有识别到语音")
while True:
rec()
request = listen()