import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart' as stt;
class VoiceMessageScreen extends StatefulWidget {
@override
_VoiceMessageScreenState createState() => _VoiceMessageScreenState();
}
class _VoiceMessageScreenState extends State<VoiceMessageScreen> {
stt.SpeechToText speechToText = stt.SpeechToText();
bool _isListening = false;
String _speechText = '';
@override
void dispose() {
super.dispose();
speechToText.stopListening();
}
void _startListening() async {
bool available = await speechToText.initialize();
if (available) {
setState(() => _isListening = true);
speechToText.listen(onResult: (result) {
setState(() => _speechText = result.recognizedWords);
});
}
}
void _stopListening() {
speechToText.stopListening();
setState(() => _isListening = false);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('语音消息'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(_speechText),
SizedBox(height: 20.0),
_isListening
? IconButton(
icon: Icon(Icons.mic),
color: Colors.red,
onPressed: _stopListening,
iconSize: 48.0,
)
: IconButton(
icon: Icon(Icons.mic_none),
color: Colors.grey,
onPressed: _startListening,
iconSize: 48.0,
),
],
),
),
);
}
}
这段代码使用了speech_to_text
插件,并展示了如何在Flutter应用中实现基本的语音识别功能。代码中包含了初始化、开始和停止监听语音的逻辑,并且在用户停止说话时更新UI显示识别的文本。在dispose
方法中确保当Widget不再使用时停止监听,以避免资源泄露。