文字轉語音 (TTS) 技術讓應用程式能「朗讀」動態文字內容。本文介紹如何在 ASP.NET 中整合 Microsoft Speech Application SDK 1.1 (SASDK),實現伺服器端語音合成並串流至用戶端播放。
Microsoft.Speech 命名空間)。Microsoft LH TTS (中文)、Microsoft Anna (英文) 等。public class TTSHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string text = context.Request["text"];
string voice = context.Request["voice"]; // 可選:指定語音名稱
if (string.IsNullOrEmpty(text)) return;
using (SpeechSynthesizer synth = new SpeechSynthesizer())
{
if (!string.IsNullOrEmpty(voice))
synth.SelectVoice(voice);
else
synth.SelectVoiceByHints(VoiceGender.NotSet, VoiceAge.NotSet, 0, CultureInfo.CurrentUICulture);
synth.Rate = 0; // 語速 -10~10
synth.Volume = 100; // 音量 0~100
// 產生 WAV 記憶體串流
using (MemoryStream ms = new MemoryStream())
{
synth.SetOutputToWaveStream(ms);
synth.Speak(text);
ms.Position = 0;
context.Response.Clear();
context.Response.ContentType = "audio/wav";
context.Response.AddHeader("Content-Length", ms.Length.ToString());
ms.WriteTo(context.Response.OutputStream);
}
}
}
public bool IsReusable => false;
}
<audio controls src="TTSHandler.ashx?text=歡迎使用語音合成系統&voice=Microsoft LH TTS"></audio>
// 或 JavaScript 動態播放
fetch('TTSHandler.ashx?text=' + encodeURIComponent(txt))
.then(r => r.blob())
.then(b => new Audio(URL.createObjectURL(b)).play());
伺服器端 TTS 雖需授權與資源管理,但在可控環境下提供穩定、一致的語音體驗,是企業級應用的重要選項。