#!/usr/bin/env python3 """ Play a WAV file through the G1 robot's speaker. Requirements: - WAV file must be 16kHz, mono, 16-bit PCM Usage: python test_speaker_wav.py en7 path/to/audio.wav """ import sys import time import struct from unitree_sdk2py.core.channel import ChannelFactoryInitialize from unitree_sdk2py.g1.audio.g1_audio_client import AudioClient def read_wav(filename): """Read WAV file and return PCM data.""" try: with open(filename, 'rb') as f: def read(fmt): return struct.unpack(fmt, f.read(struct.calcsize(fmt))) # Read RIFF header chunk_id, = read(' ") print("Example: python3 test_speaker_wav.py en7 audio.wav") print("\nWAV file requirements:") print(" - Sample rate: 16000 Hz") print(" - Channels: 1 (mono)") print(" - Bit depth: 16-bit") sys.exit(1) network_interface = sys.argv[1] wav_path = sys.argv[2] # Initialize communication print(f"Initializing on {network_interface}...") ChannelFactoryInitialize(0) # Create audio client audio_client = AudioClient() audio_client.SetTimeout(10.0) audio_client.Init() print("Audio client initialized!") # Read WAV file print(f"Reading WAV file: {wav_path}") pcm_list, sample_rate, num_channels, is_ok = read_wav(wav_path) if not is_ok: print("[ERROR] Failed to read WAV file") sys.exit(1) print(f"WAV info:") print(f" - Sample rate: {sample_rate} Hz") print(f" - Channels: {num_channels}") print(f" - Size: {len(pcm_list)} bytes") # Verify format if sample_rate != 16000: print(f"[ERROR] Sample rate must be 16000 Hz, got {sample_rate} Hz") print("Use ffmpeg to convert:") print(f" ffmpeg -i input.wav -ar 16000 -ac 1 -sample_fmt s16 output.wav") sys.exit(1) if num_channels != 1: print(f"[ERROR] Must be mono (1 channel), got {num_channels} channels") print("Use ffmpeg to convert:") print(f" ffmpeg -i input.wav -ar 16000 -ac 1 -sample_fmt s16 output.wav") sys.exit(1) # Play audio print("Playing audio...") play_pcm_stream(audio_client, pcm_list, "test_wav") # Wait for playback to finish duration_seconds = len(pcm_list) / (16000 * 2) # 16kHz, 16-bit (2 bytes) print(f"Waiting {duration_seconds:.1f} seconds for playback...") time.sleep(duration_seconds + 1) # Stop playback print("Stopping playback...") audio_client.PlayStop("test_wav") print("Done!") if __name__ == "__main__": main()