import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
class TextToSpeechDemo extends StatefulWidget {
@override
_TextToSpeechDemoState createState() => _TextToSpeechDemoState();
}
class _TextToSpeechDemoState extends State<TextToSpeechDemo> {
FlutterTts flutterTts = FlutterTts();
String _speech = '';
@override
void dispose() {
super.dispose();
flutterTts.stop();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter TTS 示例'),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
TextField(
onChanged: (text) {
setState(() {
_speech = text;
});
},
decoration: InputDecoration(
border: OutlineInputBorder(),
hintText: '输入文本',
),
),
RaisedButton(
onPressed: () {
flutterTts.setLanguage("zh-CN");
flutterTts.speak(_speech);
},
child: Text('合成语音'),
),
],
),
),
);
}
}
这段代码演示了如何在Flutter应用中集成Flutter TTS插件,实现文本转语音功能。用户可以在文本框输入文本,点击按钮后,文本将通过语音合成器读出。代码中使用FlutterTts
类来控制语音合成,并在dispose
方法中确保当控件卸载时停止语音播放。