在 PC 上通過語音替代鼠標操作 C/S 架構的 WinForm 桌面程序,核心是語音識別 → 指令解析 → UI 自動化/直接調用。
| 層級 | 技術/庫 | 說明 |
|---|---|---|
| 語音識別 | System.Speech.Recognition (.NET 內建) Microsoft Speech Platform / Windows.Media.SpeechRecognition (UWP) 第三方:iFlytek, 百度語音, Azure Speech | 內建免費離線,準確率一般;雲端準確率高但需網絡 |
| 指令映射 | GrammarBuilder / SrgsDocument 定義語法 或關鍵詞匹配 + 自然語言理解 (LUIS/Rasa) | 簡單場景用 Grammar 列舉指令;複雜場景用 NLU |
| UI 控制 | 1. 直接調用業務邏輯方法(推薦) 2. UI Automation (System.Windows.Automation) 3. SendKeys / 模擬鼠標 (不推薦) | 解耦:語音層調用 Service 層,不依賴 UI 元素 |
// 1. 定義指令與動作映射
public class VoiceCommand {
public string Phrase { get; set; } // "打開用戶管理"
public string ActionName { get; set; } // "OpenUserManagement"
public Dictionary<string, string> Parameters { get; set; }
}
// 2. 語音識別服務
public class SpeechService {
private SpeechRecognitionEngine _engine;
private Dictionary<string, Action<VoiceCommand>> _handlers;
public SpeechService() {
_engine = new SpeechRecognitionEngine(new CultureInfo("zh-CN"));
_handlers = new Dictionary<string, Action<VoiceCommand>>();
LoadGrammar();
}
private void LoadGrammar() {
var choices = new Choices();
choices.Add("打開用戶管理", "關閉窗口", "新增記錄", "查詢數據"); // 可從配置加載
var gb = new GrammarBuilder(choices);
_engine.LoadGrammar(new Grammar(gb));
_engine.SpeechRecognized += OnRecognized;
_engine.SetInputToDefaultAudioDevice();
_engine.RecognizeAsync(RecognizeMode.Multiple);
}
private void OnRecognized(object sender, SpeechRecognizedEventArgs e) {
if (e.Result.Confidence < 0.7) return; // 置信度過濾
string text = e.Result.Text;
if (_handlers.TryGetValue(text, out var handler)) {
handler(new VoiceCommand { Phrase = text, ActionName = text });
}
}
public void Register(string phrase, Action<VoiceCommand> handler) {
_handlers[phrase] = handler;
}
}
// 3. 業務層註冊指令(解耦 UI)
public class UserService {
public void OpenUserManagement() { /* 打開窗口邏輯 */ }
public void QueryData(string keyword) { /* 查詢邏輯 */ }
}
// 4. 程序入口整合
static class Program {
[STAThread]
static void Main() {
Application.EnableVisualStyles();
var speech = new SpeechService();
var userSvc = new UserService();
speech.Register("打開用戶管理", _ => userSvc.OpenUserManagement());
speech.Register("查詢數據", cmd => userSvc.QueryData("default"));
Application.Run(new MainForm());
}
}
SemanticResultKey 提取參數(如「查詢 AudioLevelUpdated 監控音量,動態調整靈敏度。