python写一个语音控制灯的开关
时间: 2024-05-03 07:17:16 浏览: 234
智能语音控制风扇灯代码
要实现语音控制灯的开关,需要用到语音识别和控制硬件的库。以下是一个基于Python的语音控制灯的示例代码,假设使用的是树莓派和GPIO控制灯的开关。
首先需要安装Python的语音识别库和GPIO控制库:
```
pip install speechrecognition
pip install RPi.GPIO
```
然后可以使用以下代码实现语音控制灯的开关:
```python
import speech_recognition as sr
import RPi.GPIO as GPIO
# 设置GPIO口
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
led_pin = 18
GPIO.setup(led_pin, GPIO.OUT)
# 初始化语音识别器
r = sr.Recognizer()
while True:
# 听取语音命令
with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source)
try:
# 识别语音命令
command = r.recognize_google(audio, language='zh-CN')
print("Google Speech Recognition thinks you said: " + command)
# 根据命令控制灯
if "开灯" in command:
GPIO.output(led_pin, GPIO.HIGH)
print("LED on")
elif "关灯" in command:
GPIO.output(led_pin, GPIO.LOW)
print("LED off")
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))
```
代码执行后,程序会一直监听语音命令。当听到“开灯”时,程序会打开GPIO口控制的LED灯;当听到“关灯”时,程序会关闭LED灯。
阅读全文