host = getenv('AUDIO_MUSIC_HOST') ?: '192.168.42.4'; $this->port = (int)(getenv('AUDIO_MUSIC_PORT') ?: 8888); $this->sn = getenv('AUDIO_SN') ?: 'ls20://0202AD1AE849'; $this->tid = getenv('AUDIO_TID') ?: '234'; $this->vol = (int)(getenv('AUDIO_VOL') ?: 50); $this->ttsUrl = getenv('AUDIO_TTS_URL') ?: 'http://192.168.42.139:10008/tts_xf.single'; $this->ttsVoice = getenv('AUDIO_TTS_VOICE') ?: 'xiaoyan'; $this->ttsSpeed = (int)(getenv('AUDIO_TTS_SPEED') ?: 50); $this->ttsVolume = (int)(getenv('AUDIO_TTS_VOLUME') ?: 100); } public function sendText(string $text): bool { // $uri = $this->ttsUrl . '?' . http_build_query([ // 'text' => $text, // 'voice_name' => $this->ttsVoice, // 'speed' => $this->ttsSpeed, // 'volume' => $this->ttsVolume, // ]); $host = getenv('LOCAL_IP') ?: '192.168.42.168'; $uri = 'http://' . $host . ':8787/' . $text; return $this->sendCommand('songs_queue_append', [ 'tid' => $this->tid, 'vol' => $this->vol, 'urls' => [ [ 'name' => 'G.mp3', 'uri' => $uri, ] ] ]); } private function sendCommand(string $name, ?array $params = null): bool { $payload = [ 'sn' => $this->sn, 'type' => 'req', 'name' => $name, ]; if ($params !== null) { $payload['params'] = $params; } $json = json_encode($payload, JSON_UNESCAPED_UNICODE); if (!$json) { return false; } $socket = @fsockopen($this->host, $this->port, $errno, $errstr, 5); if (!$socket) { echo "音乐设备连接失败: {$errstr} ({$errno})\n"; return false; } $body = $json; $request = "POST / HTTP/1.1\r\n" . "Host: {$this->host}:{$this->port}\r\n" . "Content-Type: application/json\r\n" . "Content-Length: " . strlen($body) . "\r\n" . "Connection: close\r\n" . "\r\n" . $body; fwrite($socket, $request); fflush($socket); $response = ''; while (!feof($socket)) { $response .= fread($socket, 4096); } fclose($socket); return $response !== false && strlen($response) > 0; } }