You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让WinForm打开时异步语音识别方法持续运行?

解决Azure Speech SDK持续语音识别问题

你的代码里用了RecognizeOnceAsync(),这个方法本来就只做单次语音识别,所以只能触发一次。要实现持续识别直到窗体关闭,需要改用连续识别模式,同时处理好UI线程更新和资源释放,具体修改如下:

关键改动说明

  • 将SpeechRecognizer声明为窗体类的成员变量,方便在整个生命周期内控制识别启停
  • 注册Recognized事件接收每次识别结果,替代单次调用的方式
  • 用StartContinuousRecognitionAsync()启动持续识别,而非单次识别方法
  • 识别事件在后台线程触发,更新WinForm控件时必须用Invoke()切换到UI线程
  • 在窗体关闭时停止识别并释放资源,避免内存泄漏

修改后的完整代码

using System;
using System.Windows.Forms;
using Microsoft.CognitiveServices.Speech.Audio;
using Microsoft.CognitiveServices.Speech;

namespace Project_01
{
    public partial class form1 : Form
    {
        // 声明类级别的SpeechRecognizer,方便全局控制
        private SpeechRecognizer _speechRecognizer;

        public form1()
        {
            InitializeComponent();
            // 绑定窗体关闭事件,用于停止识别
            this.FormClosing += Form1_FormClosing;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 停止识别并释放资源
            _speechRecognizer?.StopContinuousRecognitionAsync().Wait();
            _speechRecognizer?.Dispose();
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter && textBox1.Text != "")
            {
                textBox2.Focus();
            }
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter && textBox2.Text != "")
            {
                button1_Click(sender, e);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void OutputSpeechRecognitionResult(SpeechRecognitionResult speechRecognitionResult)
        {
            // 跨线程更新UI,必须用Invoke
            this.Invoke(new Action(() =>
            {
                switch (speechRecognitionResult.Reason)
                {
                    case ResultReason.RecognizedSpeech:
                        textBox1.Text = speechRecognitionResult.Text;
                        break;
                    case ResultReason.NoMatch:
                        textBox1.Text = "NOMATCH: 无法识别语音内容。";
                        break;
                    case ResultReason.Canceled:
                        var cancellation = CancellationDetails.FromResult(speechRecognitionResult);
                        textBox1.Text = $"识别取消: {cancellation.Reason}";
                        break;
                }
            }));
        }

        private async Task StartContinuousRecognition()
        {
            var speechConfig = SpeechConfig.FromSubscription("Azure key", "Region");
            speechConfig.SpeechRecognitionLanguage = "en-US";

            var audioConfig = AudioConfig.FromDefaultMicrophoneInput();
            _speechRecognizer = new SpeechRecognizer(speechConfig, audioConfig);

            // 注册识别结果事件
            _speechRecognizer.Recognized += (s, e) =>
            {
                if (e.Result != null)
                {
                    OutputSpeechRecognitionResult(e.Result);
                }
            };

            // 启动持续识别
            await _speechRecognizer.StartContinuousRecognitionAsync();
        }

        private async void form1_Load(object sender, EventArgs e)
        {
            await StartContinuousRecognition();
        }
    }
}

额外注意事项

  • 确保你的Azure Speech资源密钥和区域填写正确,否则会导致识别失败
  • 如果需要追加识别内容而非覆盖,可以把textBox1.Text = speechRecognitionResult.Text改成textBox1.AppendText(speechRecognitionResult.Text + Environment.NewLine)
  • 可以根据需求添加识别启动/停止的按钮,而不是在窗体加载时自动启动

内容的提问来源于stack exchange,提问作者Zuraiz Ahmad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:12:48