Elena Tang
Published

Ask ReSpeaker to Play Music

Experience ReSpeaker XMOS XVF3800’s DoA feature, set a voice command, and let it play music for you—smart control made easy!

BeginnerProtip1 hour91
Ask ReSpeaker to Play Music

Things used in this project

Hardware components

Seeed Studio ReSpeaker XMOS XVF3800 with XIAO ESP32S3
A professional and powerful 4-mic circular array based on the XMOS XVF3800. Equipped with Seeed Studio XIAO ESP32S3, it enables clear and precise target voice capture in noisy environments. Features 360° far-field voice pickup (up to 5m), AEC, AGC, DoA, VAD, de-reverberation, beamforming, and noise suppression.
×1

Software apps and online services

VS Code
Microsoft VS Code

Story

Read more

Code

Music Player

Python
import speech_recognition as sr
import pygame
import time
import os

# 配置区域
MUSIC_FILE = r"C:\Users\seeed\Documents\WeChat Files\wxid_7lit73aglpqc12\FileStorage\File\2025-07\01.如果我们不曾相遇.wav"  # 确保路径正确
START_CMD = "start playing music"
STOP_CMD = "stop playing music"
# 指令打桩
is_stub_debug = False

# 初始化音频系统
pygame.mixer.init(frequency=44100, size=32, channels=2, buffer=4096)  # 明确参数
is_playing = False

# 检查文件是否存在
if not os.path.exists(MUSIC_FILE):
    print(f"错误:文件不存在 - {MUSIC_FILE}")
    exit()

r = sr.Recognizer()
with sr.Microphone() as mic:
    print("系统就绪...")
    r.adjust_for_ambient_noise(mic)
    
    try:
        while True:
            print("\n等待指令...")
            try:
                audio = r.listen(mic, timeout=12, phrase_time_limit=3)
                command = r.recognize_google(audio).lower()
                if is_stub_debug:
                    command = START_CMD.lower()
                print(f"识别到: {command}")
                
                if START_CMD in command and not is_playing:
                    pygame.mixer.music.load(MUSIC_FILE)
                    pygame.mixer.music.play()
                    is_playing = True
                    print("▶️ 音乐播放中...")
                    
                elif STOP_CMD in command and is_playing:
                    pygame.mixer.music.stop()
                    is_playing = False
                    print("⏹️ 音乐已停止")
                    
            except sr.UnknownValueError:
                print("未能识别语音")
            except sr.RequestError as e:
                print(f"语音服务错误: {e}")
            except pygame.error as e:
                print(f"音频错误: {e}")
                
            time.sleep(0.1)
            
    except KeyboardInterrupt:
        if is_playing:
            pygame.mixer.music.stop()
        print("\n程序退出")

Credits

Elena Tang
1 project • 1 follower

Comments