using SpeechLib;
public class SapiTts {
private SpVoice _voice = new SpVoice();
public void Speak(string text, bool async = true) {
_voice.Speak(text, async ? SpeechVoiceSpeakFlags.SVSFlagsAsync : SpeechVoiceSpeakFlags.SVSFDefault);
}
public void SpeakChinese(string text) {
SelectVoice("Chinese");
Speak(text);
}
public void SpeakEnglish(string text) {
SelectVoice("English");
Speak(text);
}
private void SelectVoice(string langHint) {
foreach (ISpeechObjectToken tok in _voice.GetVoices("", "")) {
if (tok.GetDescription().IndexOf(langHint, StringComparison.OrdinalIgnoreCase) >= 0) {
_voice.Voice = tok;
break;
}
}
}
public int Volume { get => _voice.Volume; set => _voice.Volume = value; } // 0-100
public int Rate { get => _voice.Rate; set => _voice.Rate = value; } // -10~10
public void Pause() => _voice.Pause();
public void Resume() => _voice.Resume();
public void Stop() => _voice.Speak("", SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
}
using System.Speech.Synthesis;
public class NetTts {
private SpeechSynthesizer _synth = new SpeechSynthesizer();
public void Speak(string text) => _synth.SpeakAsync(text);
public void SpeakSync(string text) => _synth.Speak(text);
public void SelectVoice(string cultureName) {
foreach (var v in _synth.GetInstalledVoices()) {
if (v.VoiceInfo.Culture.Name.StartsWith(cultureName)) {
_synth.SelectVoice(v.VoiceInfo.Name);
break;
}
}
}
public int Volume { get => _synth.Volume; set => _synth.Volume = value; }
public int Rate { get => _synth.Rate; set => _synth.Rate = value; }
public void Pause() => _synth.Pause();
public void Resume() => _synth.Resume();
public void Stop() => _synth.SpeakAsyncCancelAll();
}
public void SpeakMixed(string text) {
var segments = SplitByLanguage(text); // 依字元範圍切分
foreach (var (seg, lang) in segments) {
SelectVoice(lang);
Speak(seg);
}
}
| 項目 | SAPI COM | System.Speech |
|---|---|---|
| 部署 | 需 COM 註冊 | 純 Managed |
| 語音選擇 | Token 介面 | InstalledVoices 集合 |
| 非同步 | SVSFlagsAsync | SpeakAsync |
| 現代化 | 維護模式 | 持續更新 |
新專案優先 System.Speech.Synthesis;需支援 XP 或特定 SAPI 5.4 功能才用 COM。雲端級 TTS 請評估 Azure Cognitive Services / AWS Polly。