Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

How to highlight the current word dynamically using flutter text to speech plugin

Here's the code to get current word but how should I highlight it.

    _flutterTts.setProgressHandler((String text, int startOffset, int endOffset, String word) {
  setState(() {
    _currentWord = word;
  });
});
question from:https://stackoverflow.com/questions/66061777/how-to-highlight-the-current-word-dynamically-using-flutter-text-to-speech-plugi

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Check out https://github.com/dlutton/flutter_tts/discussions/193, there is a linked gist that should help you achieve what you're requesting.

As most have mentioned, use RichText with TextSpan. Below is the primary parts of the code that is dynamically highlighting the word for you.

int start = 0;
int end = 0;

flutterTts.setProgressHandler(
  (String text, int startOffset, int endOffset, String word) {
    setState(() {
      start = startOffset;
      end = endOffset;
  });
});


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            appBar: AppBar(
              title: Text('Flutter TTS'),
            ),
            body: SingleChildScrollView(
                scrollDirection: Axis.vertical,
                child: Column(children: [
                  _inputSection(),
                  ttsState == TtsState.playing
                      ? _textFromInput(start, end)
                      : Text(""),
                  _btnSection(),
                  languages != null ? _languageDropDownSection() : Text(""),
                  _buildSliders()
                ]))));
  }

Widget _textFromInput(int start, int end) => Container(
      alignment: Alignment.topCenter,
      padding: EdgeInsets.only(top: 25.0, left: 25.0, right: 25.0),
      child: RichText(
        textAlign: TextAlign.center,
        text: TextSpan(children: <TextSpan>[
          TextSpan(
              text: _newVoiceText != null && start != 0
                  ? _newVoiceText.substring(0, start)
                  : "",
              style: TextStyle(color: Colors.black)),
          TextSpan(
              text: _newVoiceText != null
                  ? _newVoiceText.substring(start, end)
                  : "",
              style: TextStyle(color: Colors.red, fontWeight: FontWeight.bold)),
          TextSpan(
              text: _newVoiceText != null ? _newVoiceText.substring(end) : "",
              style: TextStyle(color: Colors.black)),
        ]),
      ));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...