Monday, April 4, 2022

Flutter Tutorial: Create Speech to Text

 On this tutorial, we will learn to create a speech to text apps using Flutter. Just like other TTS, spech to text a very helpful and unique feature that can you add to your apps.

Step 1. Add dependencies
dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  speech_to_text:

and import this packages

import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:speech_to_text/speech_to_text.dart';
Step 2. In your main.dart

Create a speech to text variables.

SpeechToText _speechToText = SpeechToText();
bool _speechEnabled = false;
String _lastWords = '';
Step 3. Initialize the function
@override
  void initState() {
    super.initState();
    _initSpeech();
  }

  /// This has to happen only once per app
  void _initSpeech() async {
    _speechEnabled = await _speechToText.initialize();
    setState(() {});
  }
Step 4. Add the listening function
void _startListening() async {
    await _speechToText.listen(onResult: _onSpeechResult);
    setState(() {});  // so that the changes are visible on screen
  }
  
void _onSpeechResult(SpeechRecognitionResult result) {
    setState(() {
      _lastWords = result.recognizedWords;   // result variable stores all the data.
    });
  }

 /// Manually stop the active speech recognition session
  /// Note that there are also timeouts that each platform enforces
  /// and the SpeechToText plugin supports setting timeouts on the
  /// listen method.
  void _stopListening() async {
    await _speechToText.stop();
    setState(() {});
  }

Step 5. Create the UI

Add to your desired frames:

Expanded(
 child: Container(
 padding: EdgeInsets.all(16),
 child: Text(
 // If listening is active show the recognized words
 _speechToText.isListening
     ? '$_lastWords'
                           : _speechEnabled
                          ? 'Tap the microphone to start listening...'
                          : 'Speech not available',
                ),
              ),

Add the floating button

floatingActionButton: FloatingActionButton(
onPressed:
// If not yet listening for speech start, otherwise stop
_speechToText.isNotListening ? _startListening : _stopListening,
tooltip: 'Listen',
child: Icon(_speechToText.isNotListening ? Icons.mic_off : Icons.mic),
),
I hope you can implement this tutorial in your apps.

0 comments:

Post a Comment