應用場景
- 電子書朗讀
- 英文聽力練習
- 單字發音學習
- 無障礙輔助工具
前置需求
- 安裝 Microsoft TTS (SAPI 5.x) — 金山詞霸等軟體通常已內建。
- 確認
%windir%\speech\vtxtauto.tlb 存在。
步驟 1:將 COM TypeLib 轉為 .NET 組件
tlbimp vtxtauto.tlb /silent /namespace:mstts /out:mstts.dll
/namespace:mstts 指定產生的命名空間。
/out 指定輸出組件名稱。
步驟 2:建立封裝類別 Speech.cs
// Speech.cs
using System;
using mstts; // 匯入 tlbimp 產生的命名空間
namespace Bedlang {
public class Speech {
private VTxtAuto vTxtAutoEx;
public Speech() {
vTxtAutoEx = new VTxtAuto();
vTxtAutoEx.Register("", ""); // 註冊 COM 元件(若需授權碼填入此處)
}
public void Speak(string text) {
vTxtAutoEx.Speak(text, 0); // 0 = 同步朗讀
}
}
}
步驟 3:編譯封裝組件
csc /target:library /out:Bedlang.dll Speech.cs /r:mstts.dll
/r:mstts.dll 參考 COM 互操作組件。
- 產出
Bedlang.dll 供上層應用參考。
步驟 4:WinForms 示範應用 demo.cs
// demo.cs
using System;
using System.Drawing;
using System.Windows.Forms;
using Bedlang;
namespace Bedlang {
public class DemoForm : Form {
private Label label1;
private TextBox textBox1;
private Button button1;
private Container components = null;
public DemoForm() { InitializeComponent(); }
protected override void Dispose(bool disposing) {
if (disposing && components != null) components.Dispose();
base.Dispose(disposing);
}
private void InitializeComponent() {
this.label1 = new Label();
this.textBox1 = new TextBox();
this.button1 = new Button();
this.SuspendLayout();
// label1
this.label1.Location = new Point(24, 16);
this.label1.Name = "label1";
this.label1.Size = new Size(120, 23);
this.label1.TabIndex = 0;
this.label1.Text = "輸入要朗讀的文字:";
// textBox1
this.textBox1.Location = new Point(24, 48);
this.textBox1.Name = "textBox1";
this.textBox1.Size = new Size(248, 21);
this.textBox1.TabIndex = 1;
// button1
this.button1.Location = new Point(112, 112);
this.button1.Name = "button1";
this.button1.TabIndex = 2;
this.button1.Text = "朗讀";
this.button1.Click += new EventHandler(this.button1_Click);
// Form
this.AutoScaleBaseSize = new Size(6, 14);
this.ClientSize = new Size(292, 197);
this.Controls.AddRange(new Control[] { this.button1, this.textBox1, this.label1 });
this.Name = "DemoForm";
this.Text = "TTS Demo";
this.ResumeLayout(false);
}
[STAThread]
static void Main() { Application.Run(new DemoForm()); }
private void button1_Click(object sender, EventArgs e) {
Speech s = new Speech();
if (textBox1.Text.Length == 0)
s.Speak("Please input letter.");
else
s.Speak(textBox1.Text);
}
}
}
步驟 5:編譯與執行
csc demo.cs /r:Bedlang.dll
# 或使用 VS.NET 直接建置專案
- 執行
demo.exe,輸入文字點擊「朗讀」即可聽見合成語音。
進階擴充方向
- 支援語音引擎切換(男/女聲、多語言)。
- 調整語速、音量、音調(
VTxtAuto 相關屬性)。
- 非同步朗讀(
Speak(text, 1))配合進度事件更新 UI。
- 整合
System.Speech.Synthesis (.NET 3.0+ 內建),免 COM 互操作。