首页 > 解决方案 > Microsoft CognitiveServices 语音类 SpeechRecognizer,无法收集结果文本

问题描述

我无法使用 SpeechRecognizer 类从 wav 文件中获取文本。

当我在下面调试代码时,我发现当我延迟时会收到文本,但它最终会崩溃。

代码不正确吗?

为了等待所有结果并将它们收集到作为字段变量的 totalText 中,我错过了什么。

using (var audioInput = AudioConfig.FromWavFileInput(wavFile))
{
    using (var recognizer = new SpeechRecognizer(configuration, audioInput))
    {
        recognizer.Recognized += (s, e) =>
        {
            if (e.Result.Reason == ResultReason.RecognizedSpeech)
            {
                System.Diagnostics.Debug.WriteLine($"RECOGNIZED: Text={e.Result.Text}");
                totalText += e.Result.Text;

            }
            else if (e.Result.Reason == ResultReason.NoMatch)
            {
                System.Diagnostics.Debug.WriteLine($"NOMATCH: Speech could not be recognized.");
            }
        };

        recognizer.Canceled += (s, e) =>
        {
            System.Diagnostics.Debug.WriteLine($"CANCELED: Reason={e.Reason}");

            if (e.Reason == CancellationReason.Error)
            {
                System.Diagnostics.Debug.WriteLine($"CANCELED: ErrorCode={e.ErrorCode}");
                System.Diagnostics.Debug.WriteLine($"CANCELED: ErrorDetails={e.ErrorDetails}");
                System.Diagnostics.Debug.WriteLine($"CANCELED: Did you update the subscription info?");
            }

            stopRecognition.TrySetResult(0);
        };

        recognizer.SessionStarted += (s, e) =>
        {
            System.Diagnostics.Debug.WriteLine("\n    Session started event.");
        };

        recognizer.SessionStopped += (s, e) =>
        {
            System.Diagnostics.Debug.WriteLine("\n    Session stopped event.");
            System.Diagnostics.Debug.WriteLine("\nStop recognition.");
            stopRecognition.TrySetResult(0);
        };

        recognizer.SpeechEndDetected += (s, e) =>
        {
            System.Diagnostics.Debug.WriteLine($"SpeechEndDetected: Did you update the subscription info?");
            SaveFile(totalText);
            stopRecognition.TrySetResult(0);
        };

        // Starts continuous recognition. Uses StopContinuousRecognitionAsync() to stop recognition.
        await recognizer.StartContinuousRecognitionAsync().ConfigureAwait(false);

        // Waits for completion.
        // Use Task.WaitAny to keep the task rooted.
        Task.WaitAny(new[] { stopRecognition.Task });

        // Stops recognition.
        await recognizer.StopContinuousRecognitionAsync().ConfigureAwait(false);
        if (totalText != string.Empty)
        {
            SaveFile(totalText);
        }
    }
}

我最终得到了这个结果。

The program '[9312] testhost.exe' has exited with code 0 (0x0).
enter code here

标签: c#async-awaitspeech-recognitionspeech-to-textazure-cognitive-services

解决方案


对上述代码的调用是同步完成的,而不是异步的,因此会导致行为不稳定。


推荐阅读