Skip to content

Commit

Permalink
MainScreen: add possibility to stop text to speech
Browse files Browse the repository at this point in the history
Stop text to speech if play button if pressed during playing.

Signed-off-by: Oleksandr Kravchuk <dev@sashko.rv.ua>
  • Loading branch information
sashko committed May 1, 2018
1 parent 9ad3c13 commit 6107986
Showing 1 changed file with 44 additions and 3 deletions.
47 changes: 44 additions & 3 deletions lib/screens/main_screen.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import "dart:async";

import 'package:speak_nato/nato.dart';
import 'package:speak_nato/preferences.dart';
import 'package:speak_nato/screens/settings_screen.dart';
Expand All @@ -8,6 +10,8 @@ import 'package:flutter_tts/flutter_tts.dart';

double textSize;

enum TtsState { playing, stopped }

class MainScreen extends StatefulWidget {
NatoAppState createState() => new NatoAppState();
}
Expand All @@ -17,21 +21,54 @@ class NatoAppState extends State<MainScreen> {
String _phonetizedText = "";

FlutterTts tts = new FlutterTts();
TtsState ttsState = TtsState.stopped;

@override
initState() {
super.initState();
initTts();
}

initTts() async {
tts.setStartHandler(() {
setState(() {
ttsState = TtsState.playing;
});
});

tts.setCompletionHandler(() {
setState(() {
ttsState = TtsState.stopped;
});
});

tts.setErrorHandler((msg) {
setState(() {
ttsState = TtsState.stopped;
});
});
}

void onTextChanged(String str) {
setState(() {
_phonetizedText = phonetizeText(str);
});
}

pronounceText(String text) async {
Future speak(String text) async {
if (getLanguage() == null) {
return;
}

await tts.setLanguage(await getLanguage());

tts.speak(text);
var result = await tts.speak(text);
if (result == 1) setState(() => ttsState = TtsState.playing);
}

Future stop() async {
var result = await tts.stop();
if (result == 1) setState(() => ttsState = TtsState.stopped);
}

@override
Expand Down Expand Up @@ -92,7 +129,11 @@ class NatoAppState extends State<MainScreen> {
// separate words with a dot, so tts takes a pause in between words
String text =
_phonetizedText.replaceAll(new RegExp(r' '), '. ');
pronounceText(text);
if (ttsState == TtsState.stopped) {
speak(text);
} else {
stop();
}
})),
);
}
Expand Down

0 comments on commit 6107986

Please sign in to comment.