我在 flutter 中使用 speech_to_text 插件将语音转换为文本。提取的文本显示在 Textformfield 中。 这工作正常,问题是当我回来将语音转换为文本时,以前的文本被删除了。我想将新文本附加到之前的文本中。
Future<void> _listenForSpeech() async {
bool isAvailable = await _speech.initialize();
if (isAvailable) {
print("supported");
bool isListening = await _speech.listen(
onResult: (result) {
setState(() {
_isListening = true;
_textFromSpeechController.text += result.recognizedWords;
});
},
);
if (!isListening) {
setState(() {
_speechText = 'Failed to start listening';
});
}
} else {
setState(() {
_speechText = 'Speech recognition not available';
print("not supported");
});
}
}
文本表单域
TextFormField(
controller: _textFromSpeechController,
)
GestureDetector(
onTap: () {
_listenForSpeech();
startTimer();
_isListening = true;
},
child: Container(
margin: const EdgeInsets.only(top: 30),
width: 150,
height: 70,
// margin: const EdgeInsets.only(left: 10),
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage(
"assets/images/audio_rec_blue.png"))),
),
),
GestureDetector(
onTap: () {
_stopVoiceListener();
_resetTimer();
setState(() {
_isListening = false;
});
},
child: Container(
width: 200,
height: 130,
padding: EdgeInsets.zero,
decoration: const BoxDecoration(
image: DecorationImage(
image: AssetImage("assets/gifs/recording.gif"))),
),
),
方法
void _stopVoiceListener() {
if (_isListening == true) {
_isListening = false;
_speech.cancel();
// newText += "' ' ${_textFromSpeechController.text}";
}
}