簡體   English   中英

如何使用 flutter 語音轉文本提供商 class

[英]how to use flutter speech to text provider class

伙計們.....我如何使用 Speech To Text Provider 以便我可以在多個小部件中多次使用它? 我每個應用程序只能啟動一次語音到文本 session ......我知道我需要將它用作提供者 class 但我不知道如何......

我嘗試將語音轉文本,但它對我不起作用,因為我需要在多個小部件中使用它,並且我希望能夠使用回調“onstatus”和“onerror”

我不知道還能說什么,因為它要求我輸入一定數量的字母

將語音初始化為根/第一個 class 中的文本。

final SpeechToText speech = SpeechToText();
late SpeechToTextProvider speechProvider;

在 initState 中,初始化 SpeechProvider 並將語音實例傳遞給它。

speechProvider = SpeechToTextProvider(speech);

await speechProvider.initialize(); // do it in any other method and call it from initState.

在根小部件中,添加 ChangeNotifierProvider 並傳遞 SpeechToTextProvider class。

ChangeNotifierProvider<SpeechToTextProvider>.value(
      value: speechProvider, 
       child: ///

現在您可以在項目中的任何位置使用 speechToTextProvider。

現在,為了在項目中的任何地方使用它,您必須在要使用它的 class 中初始化 SpeechToTextProvider。

  late SpeechToTextProvider speechToTextProvider;
  speechToTextProvider = Provider.of<SpeechToTextProvider>(context); // do it in a didChangeDependency or any other method and call it from initState.  

現在為了開始聽

speechToTextProvider.listen(
        pauseFor: Duration(seconds: 5),
        localeId: 'en-us',
        listenFor: Duration(seconds: 5));
    StreamSubscription<SpeechRecognitionEvent> subscription =
        speechToTextProvider.stream.listen(
      (event) {
        // on every change it update
        if (event.eventType ==
            SpeechRecognitionEventType.partialRecognitionEvent) {
          if (mounted) {
            _setState!(
              () {
                toDisplayText =
                    speechToTextProvider.lastResult!.recognizedWords; // the textField or Text Widget Will be updated
                
              },
            );
          }
        }
        //on error
        else if (event.eventType == SpeechRecognitionEventType.errorEvent) {
          ///on error if some error occurs then close the dilog box here . or stop the listner
          }
        }
        //on done
        else if (event.eventType ==
            SpeechRecognitionEventType.finalRecognitionEvent) {
          //when the user stop speaking.
        }
      },
    );
  }

這樣您就可以在任何 class 或小部件中使用它。 您必須在其他 class 中重復開始監聽的過程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM