using System; using System.IO; using System.Speech.Synthesis; using System.Threading; using System.Threading.Tasks; using System.Windows.Media; using EdgeTtsSharp; using EdgeTtsSharp.Structures; namespace ClassNotify.Client.Services; public static class AudioTtsService { private static MediaPlayer? _mediaPlayer; private static MediaPlayer? _shakePlayer; private static Voice? _cachedVoice; private static readonly object _synthLock = new(); private static SpeechSynthesizer? _activeSynth; public static void Stop() { try { App.Current?.Dispatcher?.Invoke(() => { try { _mediaPlayer?.Stop(); _mediaPlayer?.Close(); _shakePlayer?.Stop(); _shakePlayer?.Close(); } catch { } }); lock (_synthLock) { try { _activeSynth?.SpeakAsyncCancelAll(); _activeSynth?.Dispose(); _activeSynth = null; } catch { } } Log("Audio playback forcefully stopped."); } catch { } } public static void PlayShakeSound() { try { var soundPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "assets", "shake_alert.mp3"); if (!File.Exists(soundPath)) { System.Media.SystemSounds.Exclamation.Play(); return; } App.Current?.Dispatcher?.InvokeAsync(() => { try { _shakePlayer?.Close(); _shakePlayer = new MediaPlayer(); _shakePlayer.Open(new Uri(soundPath)); _shakePlayer.Volume = 1.0; _shakePlayer.MediaEnded += (s, e) => _shakePlayer?.Close(); _shakePlayer.Play(); Log("Shake alert voice ('请注意!') played successfully."); } catch (Exception ex) { Log($"Shake sound playback error: {ex.Message}"); System.Media.SystemSounds.Exclamation.Play(); } }); } catch { } } private static void Log(string msg) { try { var logDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "ClassNotify", "logs"); Directory.CreateDirectory(logDir); File.AppendAllText(Path.Combine(logDir, "client.log"), $"[{DateTimeOffset.UtcNow:yyyy-MM-dd HH:mm:ss.fff}] [AudioTtsService] {msg}\r\n"); } catch { } } public static async Task PlayMessageAsync(string message, string voice = "zh-CN-XiaoxiaoNeural") { if (string.IsNullOrWhiteSpace(message)) return; string? tempFile = null; try { Log($"Requesting EdgeTTS audio synthesis. Voice: '{voice}', Text: '{message.Substring(0, Math.Min(30, message.Length))}...'"); if (_cachedVoice == null || _cachedVoice.ShortName != voice) { _cachedVoice = await EdgeTts.GetVoice(voice); Log($"Loaded voice metadata: {_cachedVoice?.ShortName}, Name={_cachedVoice?.Name}"); } if (_cachedVoice != null) { tempFile = Path.Combine(Path.GetTempPath(), $"classnotify_tts_{Guid.NewGuid():N}.mp3"); using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); await EdgeTts.SaveAudioToFile(_cachedVoice, message, tempFile, new PlaybackSettings(), cts.Token); if (File.Exists(tempFile)) { var fileLen = new FileInfo(tempFile).Length; Log($"EdgeTTS audio generated: {tempFile} ({fileLen} bytes)"); if (fileLen > 0) { await App.Current.Dispatcher.InvokeAsync(() => { try { _mediaPlayer?.Close(); _mediaPlayer = new MediaPlayer(); _mediaPlayer.MediaOpened += (s, e) => Log("MediaPlayer opened file successfully."); _mediaPlayer.MediaFailed += (s, e) => Log($"MediaPlayer playback error: {e.ErrorException?.Message}"); _mediaPlayer.Open(new Uri(tempFile)); _mediaPlayer.Volume = 1.0; _mediaPlayer.MediaEnded += (s, e) => { try { _mediaPlayer.Close(); if (File.Exists(tempFile)) File.Delete(tempFile); Log("MediaPlayer playback ended."); } catch { } }; _mediaPlayer.Play(); Log("MediaPlayer.Play() invoked on UI dispatcher."); } catch (Exception ex) { Log($"MediaPlayer invocation failed: {ex.Message}"); } }); return; } } } } catch (Exception ex) { Log($"EdgeTTS synthesis failed: {ex.Message}. Falling back to Windows SAPI SpeechSynthesizer..."); if (!string.IsNullOrEmpty(tempFile) && File.Exists(tempFile)) { try { File.Delete(tempFile); } catch { } } } // Local Fallback: Windows SpeechSynthesizer ThreadPool.QueueUserWorkItem(_ => { try { Log("Executing local SAPI SpeechSynthesizer fallback..."); SpeechSynthesizer synth; lock (_synthLock) { _activeSynth?.Dispose(); _activeSynth = new SpeechSynthesizer(); synth = _activeSynth; } synth.SetOutputToDefaultAudioDevice(); synth.Rate = 0; synth.Volume = 100; synth.Speak(message); Log("Local SAPI SpeechSynthesizer playback finished."); } catch (Exception ex) { Log($"SpeechSynthesizer fallback failed: {ex.Message}"); } }); } }