xml code
----------------------------------------------
<Page
x:Class="MyApp.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MyApp"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<StackPanel>
<TextBox Name="txtInput" Height="100" TextWrapping="Wrap"/>
<Button Margin="0,15,0,10" Content="点击这里,开始识别" Click="onClick" HorizontalAlignment="Stretch"/>
<TextBlock Name="tbDisplay" FontSize="16" Margin="3,13,0,0" Foreground="Yellow"/>
</StackPanel>
</Page>
C# code
-----------------------------------------------------
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached.
/// This parameter is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// TODO: Prepare page for display here.
// TODO: If your application contains multiple pages, ensure that you are
// handling the hardware Back button by registering for the
// Windows.Phone.UI.Input.HardwareButtons.BackPressed event.
// If you are using the NavigationHelper provided by some templates,
// this event is handled for you.
}
private async void onClick(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
btn.IsEnabled = false;
using (SpeechRecognizer recognizer = new SpeechRecognizer())
{
try
{
// 编译所有语法协定
SpeechRecognitionCompilationResult compilationResult = await recognizer.CompileConstraintsAsync();
if (compilationResult.Status == SpeechRecognitionResultStatus.Success)
{
// 开始识别
SpeechRecognitionResult recogResult = await recognizer.RecognizeAsync();
// 显示识别结果
if (recogResult.Status == SpeechRecognitionResultStatus.Success)
{
tbDisplay.Text = "识别完成。";
txtInput.Text = recogResult.Text;
}
}
}
catch (Exception ex)
{
tbDisplay.Text = "异常:" + ex.Message;
}
}
btn.IsEnabled = true;
}
}