42 lines
1.1 KiB
Dart
42 lines
1.1 KiB
Dart
import 'package:flutter/material.dart';
|
|
import 'package:flutter_tts/flutter_tts.dart';
|
|
import 'package:get/get.dart';
|
|
|
|
class TextToSpeechController extends GetxController {
|
|
final flutterTts = FlutterTts();
|
|
|
|
// Initialize TTS in initState
|
|
@override
|
|
void onInit() {
|
|
super.onInit();
|
|
initTts();
|
|
}
|
|
|
|
// Dispose of TTS when controller is closed
|
|
@override
|
|
void onClose() {
|
|
super.onClose();
|
|
flutterTts.completionHandler;
|
|
}
|
|
|
|
// Function to initialize TTS engine
|
|
Future<void> initTts() async {
|
|
String? lang =
|
|
WidgetsBinding.instance.platformDispatcher.locale.countryCode;
|
|
await flutterTts.setLanguage(lang!); //'en-US' Set language
|
|
await flutterTts.setSpeechRate(0.5); // Adjust speech rate
|
|
await flutterTts.setVolume(1.0); // Set volume
|
|
}
|
|
|
|
// Function to speak the given text
|
|
Future<void> speakText(String text) async {
|
|
try {
|
|
await flutterTts.speak(text);
|
|
} catch (error) {
|
|
// Handle error gracefully, e.g., show a message
|
|
Get.snackbar('Error', 'Failed to speak text: $error');
|
|
print('Failed to speak text: $error');
|
|
}
|
|
}
|
|
}
|