找一个可实现的语音唤醒代码
时间: 2024-05-02 08:20:45 浏览: 184
讯飞语音唤醒示例源码
4星 · 用户满意度95%
以下是使用Python实现语音唤醒的示例代码:
1. 安装需要的库
```
pip install pyaudio
pip install SpeechRecognition
```
2. 代码实现
```python
import speech_recognition as sr
# 初始化识别器和麦克风
r = sr.Recognizer()
mic = sr.Microphone()
# 定义唤醒词和对应的响应函数
wakeup_words = ['你好', '你在吗']
def on_wakeup():
print('听到了唤醒词!')
# 定义语音识别函数
def recognize_speech():
with mic as source:
print('开始录音...')
r.adjust_for_ambient_noise(source)
audio = r.listen(source)
try:
text = r.recognize_google(audio, language='zh-CN')
print('识别结果:', text)
if text in wakeup_words:
on_wakeup()
except sr.UnknownValueError:
print('听不清楚,请再说一遍。')
except sr.RequestError as e:
print('请求出错:{0}'.format(e))
# 循环监听语音输入
with mic as source:
r.adjust_for_ambient_noise(source)
print('语音唤醒已启动')
while True:
recognize_speech()
```
以上代码会监听麦克风,如果检测到唤醒词,就会执行`on_wakeup()`函数。可以将`on_wakeup()`替换成其他需要的操作或语音交互功能实现。
阅读全文