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 {
    await flutterTts.setLanguage('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');
    }
  }
}
