Integrating speech recognition capabilities into mobile apps has become increasingly important in the era of voice assistants and voice commands. With its cross-platform framework, Flutter offers a convenient way to develop voice recognition features for users on both Android and iOS devices.
This tutorial will explore using the Flutter Speech to Text plugin to build a voice recognition app. We will discuss the Flutter plugin's features and step-by-step implementation and provide code snippets throughout the blog post.
Before building our voice recognition app, let's take a moment to understand the Flutter Speech to Text plugin and its capabilities.
The Speech to Text plugin is a library that exposes device-specific speech-to-text recognition capability. It provides classes that make it easy to utilize the speech recognition features of the underlying platform in a Flutter app. The plugin currently supports Android, iOS, and web platforms.
However, it's important to note that the plugin is primarily a voice assistant designed for handling commands and short phrases rather than continuous speech conversion or always-on listening.
Here's an overview of the platform support for the plugin:
To learn more about the Flutter Speech to Text plugin and its recent updates, we can refer to the official package README file.
To implement the voice command recognition feature in our Flutter app, we need to follow these steps:
Let's go through each step in detail.
First, we need to add the speech_to_text dependency to our pubspec.yaml file. Open the file and add the following line under the dependencies section:
1speech_to_text: ^6.5.1
Save the file and run the command flutter pub get to fetch the package.
We need to request the necessary permissions to access the device's microphone. Add the following code snippet inside your widget's class:
1import 'package:speech_to_text/speech_to_text.dart' as stt; 2 3// ... 4 5stt.SpeechToText speech = stt.SpeechToText(); 6 7Future<bool> getMicrophonePermission() async { 8 bool hasPermission = await speech.initialize( 9 onError: (error) => print('Error initializing speech recognition: $error'), 10 ); 11 12 if (!hasPermission) { 13 bool isPermissionGranted = await speech.requestPermission(); 14 15 if (!isPermissionGranted) { 16 print('Microphone permission not granted'); 17 } 18 19 return isPermissionGranted; 20 } 21 22 return true; 23}
Create an instance of speech_to_text.SpeechToText, which we'll use to request microphone permission. Then, define a method getMicrophonePermission that checks if the app has permission to access the microphone. If not, it requests permission and returns a boolean indicating whether it was granted.
Next, we need to handle the permission response. Add the following code snippet inside your widget's class:
1// ... 2 3Future<void> handlePermissionResponse(bool isPermissionGranted) async { 4 if (isPermissionGranted) { 5 // Permission granted, continue with voice recognition 6 // ... 7 } else { 8 // Permission not granted, show error message or ask the user to grant permission manually 9 // ... 10 } 11}
This method receives the boolean value indicating whether the microphone permission was granted. You can handle the logic here based on your app's requirements. For example, you can show an error message to the user or prompt them to grant permission manually through device settings.
Now, let's initialize the speech recognition object. Add the following code snippet inside your widget's class:
1// ... 2 3Future<void> initializeSpeechRecognition() async { 4 bool isPermissionGranted = await getMicrophonePermission(); 5 await handlePermissionResponse(isPermissionGranted); 6}
This method calls the getMicrophonePermission method to check and request the microphone permission, and then it calls handlePermissionResponse to handle the permission response.
Before starting speech recognition, checking if the device supports it is essential. Add the following code snippet inside your widget's class:
1// ... 2 3bool isSpeechRecognitionAvailable() { 4 return speech.isAvailable; 5}
This method checks if the speech recognition feature is available on the device using isAvailable from the speech recognition object.
To start the speech recognition process, add the text to speech following code snippet inside your widget's class:
1// ... 2 3void startSpeechRecognition() { 4 speech.listen( 5 onResult: (result) => print('Recognition result: ${result.recognizedWords}'), 6 listenFor: Duration(minutes: 1), 7 cancelOnError: true, 8 ); 9}
This method starts the speech recognition by calling the listen method from the speech recognition object. It receives a callback onResult that provides the recognized spoken words. Additionally, we specify listenFor to set a timeout for the recognition process.
The recognized speech can be handled as desired. In the previous code snippet, we printed it to the console. You can modify the code to meet your specific use case. For example, updating the UI with the recognized words, triggering specific actions, or sending the speech to a natural language processing service for further processing.
To stop the speech recognition process, add the following code snippet inside your widget's class:
1// ... 2 3void stopSpeechRecognition() { 4 speech.stop(); 5}
This method calls the stop method from the speech recognition object, which stops the ongoing speech recognition process.
Finally, cleaning up and disposing of the speech recognition object is important when we're done using it. Add the following code snippet inside your widget's class:
1// ... 2 3void disposeSpeechRecognition() { 4 speech.cancel(); 5}
This method calls the cancel method from the speech recognition object, which cancels the ongoing recognition process. It's good practice to call this method when we're finished with the speech recognition feature to clean up any resources.
Now that we have implemented the voice recognition feature let's see how we can use it in our Flutter app.
To start the speech recognition, we can call the startSpeechRecognition method. For example, we can trigger the start of the audio speech recognition process when a button is pressed:
1// ... 2 3ElevatedButton( 4 onPressed: () { 5 if (isSpeechRecognitionAvailable()) { 6 startSpeechRecognition(); 7 } else { 8 // Speech recognition not available, show error message or alternative 9 // ... 10 } 11 }, 12 child: Text('Start Listening'), 13),
Similarly, we can stop the speech recognition process when another button is pressed:
1// ... 2 3ElevatedButton( 4 onPressed: stopSpeechRecognition, 5 child: Text('Stop Listening'), 6),
Remember to clean up and dispose of the speech recognition object when we're done using it. We can call the disposeSpeechRecognition method in the dispose method of our widget:
1// ... 2 3@override 4void dispose() { 5 disposeSpeechRecognition(); 6 super.dispose(); 7}
This tutorial explored building a voice recognition app using the Flutter Speech-to-Text plugin. We learned how to add the plugin to our project, request microphone permission, handle the permission response, initialize the speech recognition object, start and stop the recognition process, record audio, handle recognition results, and dispose of the speech recognition object.
By implementing the voice recognition feature, you can add a powerful and intuitive user interface and experience to your Flutter app. The possibilities are endless, whether it's voice commands, speech-to-text input, or voice-controlled features!
Remember to refer back to the official documentation and dive deeper into integrating the Flutter Speech-to-Text plugin to explore its full capabilities. Happy coding!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.