语音识别

来源:CSDN 发布时间:Nov 15, 2020, 8:18:44 AM 原地址:https://blog.csdn.net/qq_41708190/article/details/109699444

语音识别是通过机器的音频输入设备(如麦克风)获取用户所说的内容,然后进行分析处理,最终将口头表述的内容转换为文本的过程。

要在应用程序中完成语音识别任务,需要用到SpeechRecognizer类(位于Windows.Media.SpeechRecognition命名空间)。该类的使用也比较简单,通常的过程如下:

  1. 实例化SpeechRecognizer对象。
  2. 可以向Constraints集合添加自定义的识别约束(规则),只要实现了ISpeechRecognitionConstraint接口的类型都可以,如基于SGRS文件定义的语法规则等。这一步是可选的,只有对语音识别有较为严格的要求时才会考虑自定义识别规则。
  3. 调用CompileConstraintsAsync方法编译上一步中定义的识别规则。就算没有添加自定义规则也应该调用CompileConstraintsAsync方法,因为语音识别组件也需要编译系统默认的识别规则。
  4. 调用SpeechRecognizer或者RecognizeWithUIAsync方法开始进行识别。识别结束后,会将处理结果封装在SpeechRecognitionResult对象返回。可以从SpeechRecognitionResult对象的Text属性中获得到已经识别出来的文本内容。Status属性反映语音识别的操作状态,如果为Success则表明整个识别过程顺序完成。

接下来是一个语音识别的小示例。

应用主页面的XAML代码如下:

    <StackPanel>
        <TextBox x:Name="txtInput" Height="100" TextWrapping="Wrap"/>
        <Button x:Name="btn" Content="点击这里,开始识别" Tapped="Button_Tapped"
                HorizontalAlignment="Stretch"/>
        <TextBlock x:Name="tbDisplay" FontSize="16" Margin="3,13,0,0"
                   Foreground="Yellow"/>
    </StackPanel>

单击按钮后开始进行语音识别,识别出来的结果将显示在TextBox控件中。

        private async void Button_Tapped(object sender, TappedRoutedEventArgs e)
        {
            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;
            }
        }

需要注意的是,无论开发者是否添加自定义的语法约束,在开始识别之前都应该调用CompileConstraintsAsync方法编译所有语法约束(包括系统默认的约束)。