ESP32-S3+Micropython:从零构建豆包实时语音助手
·
ESP32-S3 + MicroPython:构建豆包实时语音助手
1. 硬件准备
- 核心组件:
- ESP32-S3开发板(支持WiFi/BLE)
- I2S数字麦克风模块(如INMP441)
- 扬声器或耳机输出
- 接线示意图:
麦克风 → ESP32-S3 LRC → GPIO9 BCLK → GPIO8 DOUT → GPIO38 GND → GND VCC → 3.3V
2. 软件环境配置
# 刷入MicroPython固件
import upip
upip.install("micropython-ism330dhcx") # 安装传感器驱动
upip.install("micropython-ulab") # 安装科学计算库
3. 音频采集核心代码
from machine import I2S, Pin
# 初始化I2S麦克风
mic = I2S(
0,
sck=Pin(8),
ws=Pin(9),
sd=Pin(38),
mode=I2S.RX,
bits=16,
format=I2S.MONO,
rate=16000,
ibuf=40000
)
def record_audio(duration=3):
"""录制3秒音频"""
frames = bytearray()
for _ in range(int(16000 * duration / 256)):
frames.extend(mic.read(256))
return frames
4. 语音识别处理
import urequests
import ujson
def speech_to_text(audio_data):
"""调用云端语音识别API"""
API_URL = "https://your-speech-api.com/recognize"
headers = {"Content-Type": "audio/wav; rate=16000"}
response = urequests.post(API_URL, data=audio_data, headers=headers)
return ujson.loads(response.text)["text"]
# 示例使用
audio = record_audio()
command = speech_to_text(audio)
print("识别结果:", command)
5. 自然语言处理(豆包响应)
def get_doubao_response(query):
"""调用豆包对话API"""
API_URL = "https://api.doubao.com/chat"
payload = ujson.dumps({"query": query})
response = urequests.post(API_URL, data=payload)
return ujson.loads(response.text)["reply"]
# 示例对话
response_text = get_doubao_response(command)
print("豆包回复:", response_text)
6. 语音合成与播放
# 初始化I2S扬声器
spk = I2S(
1,
sck=Pin(12),
ws=Pin(11),
sd=Pin(13),
mode=I2S.TX,
bits=16,
format=I2S.MONO,
rate=22050
)
def text_to_speech(text):
"""调用TTS服务"""
TTS_API = "https://your-tts-service.com/synthesize"
response = urequests.post(TTS_API, data=text)
return response.content
# 播放语音
audio_response = text_to_speech(response_text)
spk.write(audio_response)
7. 完整工作流
def voice_assistant():
while True:
# 1. 语音唤醒检测
if detect_wake_word():
# 2. 录制指令
audio = record_audio(5)
# 3. 语音识别
command = speech_to_text(audio)
# 4. 获取响应
response = get_doubao_response(command)
# 5. 语音播报
speech = text_to_speech(response)
spk.write(speech)
# 启动助手
voice_assistant()
优化建议
- 唤醒词检测:
def detect_wake_word(): # 实时分析音频流,检测"豆包"唤醒词 return audio_analysis() - 低功耗模式:
# 未激活时进入深度睡眠 machine.deepsleep(1000) # 每1秒唤醒检测 - 离线命令:
if "打开灯光" in command: control_light(True) # 本地执行无需联网
关键参数配置
| 参数 | 推荐值 | 说明 |
|---|---|---|
| 采样率 | 16000 Hz | 语音识别标准采样率 |
| 音频格式 | 16-bit PCM | 兼容多数API |
| 缓冲区大小 | 40KB | 确保流畅录音 |
| 网络超时 | 5秒 | 防止阻塞 |
注意:实际开发需申请语音识别和TTS服务API密钥,并处理网络异常情况。建议使用WebSocket实现实时双向音频流传输以降低延迟。
更多推荐
所有评论(0)