如何使用 flutter text to speech 插件动态高亮当前单词

问题描述 投票:0回答:2

这是获取当前单词的代码,但我应该如何突出显示它。

    _flutterTts.setProgressHandler((String text, int startOffset, int endOffset, String word) {
  setState(() {
    _currentWord = word;
  });
});
flutter text-to-speech
2个回答
2
投票

查看https://github.com/dlutton/flutter_tts/discussions/193,有一个链接的要点可以帮助您实现您的要求。

正如大多数人提到的,将 RichText 与 TextSpan 结合使用。下面是为您动态突出显示单词的代码的主要部分。

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)),
        ]),
      ));

0
投票

我想为两种语言做这件事,但它给了我问题。对于从 api 源获取的 2 种语言,我该如何做到这一点??

© www.soinside.com 2019 - 2024. All rights reserved.