継続的なディクテーションを有効にする

Windows アプリ SDK アプリで長い形式の連続ディクテーション音声入力をキャプチャして認識する方法について説明します。

Important

音声認識には MSIX パッケージ ID が必要です。 Windows.Media.SpeechRecognition API は、アプリがパッケージ ID (パッケージ化または外部の場所でパッケージ化) で実行されている場合にのみ使用できます。 パッケージ化されていないアプリでは、これらの API を使用できません。

主要API

Overview

音声認識では、RecognizeAsyncまたはRecognizeWithUIAsyncを使用して、短い音声入力をキャプチャして認識する方法について説明します。 ディクテーションや電子メールなど、より長く継続的な音声認識セッションでは、ContinuousRecognitionSessionSpeechRecognizer プロパティを使用して、SpeechContinuousRecognitionSession オブジェクトを取得します。

ディクテーション言語のサポートは、アプリが実行されているデバイスによって異なります。 PC とノート PC の場合、ディクテーションでは en-US のみが認識されますが、Xboxは音声認識でサポートされているすべての言語を認識できます。 詳細については、「 音声認識エンジン言語を指定する」を参照してください。

セットアップ

アプリでは、継続的なディクテーション セッションを管理するために、次のオブジェクトが必要です。

  • SpeechRecognizer オブジェクトのインスタンス。
  • ディクテーション中に UI を更新するための UI ディスパッチャーへの参照。
  • ユーザーが話した蓄積された単語を追跡する方法。

認識結果をページ クラスのフィールドとして蓄積する SpeechRecognizer インスタンスと StringBuilder を宣言します。

private SpeechRecognizer speechRecognizer;
private StringBuilder dictatedTextBuilder;

WinUI 3 では、 DispatcherQueue を使用して( CoreDispatcherではなく) バックグラウンド スレッドから UI の更新をディスパッチします。

// Get the DispatcherQueue for the current thread (UI thread).
private Microsoft.UI.Dispatching.DispatcherQueue dispatcherQueue =
    Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread();

初期化

初期化中は、次の処理を行います。

  1. 音声認識エンジンを初期化します。
  2. 組み込みのディクテーション文法をコンパイルします (または、カスタム制約を追加します)。
  3. 認識イベントのイベント リスナーを設定します。
// Initialize the speech recognizer.
speechRecognizer = new SpeechRecognizer();

// Compile the default dictation grammar.
SpeechRecognitionCompilationResult result =
    await speechRecognizer.CompileConstraintsAsync();

// Subscribe to continuous recognition events.
speechRecognizer.ContinuousRecognitionSession.ResultGenerated +=
    ContinuousRecognitionSession_ResultGenerated;
speechRecognizer.ContinuousRecognitionSession.Completed +=
    ContinuousRecognitionSession_Completed;
speechRecognizer.HypothesisGenerated +=
    SpeechRecognizer_HypothesisGenerated;

dictatedTextBuilder = new StringBuilder();

認識イベントを処理する

結果が生成されました

ResultGenerated イベントは、ユーザーが話すと発生します。 認識エンジンは、音声入力の一部を定期的に渡します。 結果を受け入れるかどうかを決定するには、 Confidence プロパティを確認します。

このイベントはバックグラウンド スレッドで発生するため、 DispatcherQueue.TryEnqueue を使用して UI を更新します。

private void ContinuousRecognitionSession_ResultGenerated(
    SpeechContinuousRecognitionSession sender,
    SpeechContinuousRecognitionResultGeneratedEventArgs args)
{
    if (args.Result.Confidence == SpeechRecognitionConfidence.Medium ||
        args.Result.Confidence == SpeechRecognitionConfidence.High)
    {
        dictatedTextBuilder.Append(args.Result.Text + " ");

        dispatcherQueue.TryEnqueue(() =>
        {
            dictationTextBox.Text = dictatedTextBuilder.ToString();
            btnClearText.IsEnabled = true;
        });
    }
}

完了

Completed イベントは、継続的な認識セッションが終了したことを示します。 セッションは、 StopAsync または CancelAsyncを呼び出すとき、またはエラーが発生したとき、またはユーザーが話を停止したときに終了します。

private void ContinuousRecognitionSession_Completed(
    SpeechContinuousRecognitionSession sender,
    SpeechContinuousRecognitionCompletedEventArgs args)
{
    if (args.Status != SpeechRecognitionResultStatus.Success)
    {
        dispatcherQueue.TryEnqueue(() =>
        {
            if (args.Status == SpeechRecognitionResultStatus.TimeoutExceeded)
            {
                dictationTextBox.Text = dictatedTextBuilder.ToString();
            }
        });
    }
}

仮説が生成されました

HypothesisGenerated イベントを処理して、認識エンジンの処理中に中間結果を表示します。 これにより、最終的な結果を得る前にユーザーのフィードバックを提供することで、応答性が向上します。

private void SpeechRecognizer_HypothesisGenerated(
    SpeechRecognizer sender,
    SpeechRecognitionHypothesisGeneratedEventArgs args)
{
    string hypothesis = args.Hypothesis.Text;
    string textboxContent = dictatedTextBuilder.ToString() + " " + hypothesis + " ...";

    dispatcherQueue.TryEnqueue(() =>
    {
        dictationTextBox.Text = textboxContent;
        btnClearText.IsEnabled = true;
    });
}

認識の開始と停止

セッションを開始または停止する前に、認識エンジンの状態を確認します。

// Start continuous recognition.
if (speechRecognizer.State == SpeechRecognizerState.Idle)
{
    await speechRecognizer.ContinuousRecognitionSession.StartAsync();
}

// Stop continuous recognition (lets pending events complete).
if (speechRecognizer.State != SpeechRecognizerState.Idle)
{
    await speechRecognizer.ContinuousRecognitionSession.StopAsync();
}

すぐに取り消して保留中の結果を破棄するには、CancelAsyncの代わりにStopAsyncを呼び出します。

マルチスレッドのためにResultGeneratedを呼び出した後、CancelAsyncイベントが発生する可能性があります。 認識セッションをキャンセルするときにプライベート フィールドを設定する場合は、常に ResultGenerated ハンドラーでその値を検証します。