


























SpeechRecognition.axaml代码
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" x:Class="AvaloniaUI.SpeechRecognition" Title="SpeechRecognition"> <StackPanel Margin="10" Spacing="8"> <Label x:Name="lbl" Content="空闲..." /> <TextBlock Text="Try: '红色开', '蓝色关' ..." Opacity="0.7"/> </StackPanel> </Window>
SpeechRecognition.axaml.cs代码
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.Threading;
using System;
using System.Globalization;
using System.Linq;
using System.Speech.Recognition;
namespace AvaloniaUI;
public partial class SpeechRecognition : Window
{
private SpeechRecognitionEngine? recognizer;
public SpeechRecognition()
{
InitializeComponent();
try
{
var engine = CreateBestAvailableRecognizer();
if (engine is null)
{
SetLabel("No System.Speech recognizer installed on this machine.");
return;
}
recognizer = engine;
var grammar = new GrammarBuilder();
grammar.Append(new Choices("红色", "蓝色", "绿色", "黑色", "白色"));
grammar.Append(new Choices("开", "关"));
recognizer.LoadGrammar(new Grammar(grammar));
recognizer.SpeechDetected += (_, _) => SetLabel("Speech detected.");
recognizer.SpeechHypothesized += (_, _) => SetLabel("Speech uncertain.");
recognizer.SpeechRecognitionRejected += (_, _) => SetLabel("Speech rejected.");
recognizer.SpeechRecognized += (_, e) => SetLabel("You said: " + e.Result.Text);
recognizer.SetInputToDefaultAudioDevice();
recognizer.RecognizeAsync(RecognizeMode.Multiple);
SetLabel($"Ready. Recognizer: {recognizer.RecognizerInfo.Culture.Name}");
}
catch (Exception ex)
{
SetLabel("Init failed: " + ex.Message);
}
}
private SpeechRecognitionEngine? CreateBestAvailableRecognizer()
{
var infos = SpeechRecognitionEngine.InstalledRecognizers();
if (infos is null || infos.Count == 0)
return null;
// 你可以按需调整优先级
var preferred = new[] { "zh-CN", "en-US", "en-GB" };
var best =
infos.FirstOrDefault(x => preferred.Contains(x.Culture.Name, StringComparer.OrdinalIgnoreCase))
?? infos.First();
return new SpeechRecognitionEngine(best);
}
private void SetLabel(string text) => lbl.Content = text;
protected override void OnClosed(EventArgs e)
{
try
{
if (recognizer is not null)
{
recognizer.RecognizeAsyncCancel();
recognizer.RecognizeAsyncStop();
recognizer.Dispose();
}
}
catch { }
base.OnClosed(e);
}
}
运行效果 - 语音识别

此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。