flutter_tts는 Flutter 앱에 TTS 기능을 추가할 수 있게 해주는 플러그인입니다. 이 플러그인을 사용하면 텍스트를 음성으로 변환하여 재생할 수 있습니다. 그 과정은 대부분의 네이티브 플랫폼 기능과 유사하게 비동기적으로 처리됩니다.
flutter pub add flutter_tts
flutter_tts를 사용하기 위해 먼저 pubspec.yaml 파일에 의존성을 추가해야 합니다.
dependencies:
flutter_tts: ^latest_version
TextToSpeech 클래스
FlutterTts flutterTts = FlutterTts();
TTS 기능을 위한 객체를 생성합니다.
Future speak(String text) async
주어진 텍스트를 읽습니다. flutterTts.speak(text)를 호출하여 텍스트를 음성으로 변환하고 재생합니다.
Future stop() async
현재 읽고 있는 음성을 정지합니다. flutterTts.stop()을 호출하여 재생을 중지합니다.
StoryDetailScreen 위젯에서 사용자가 앱 바의 재생 버튼을 누를 때, tts.speak(story.content)를 호출합니다. 이는 TextToSpeech 클래스의 speak 메서드를 통해, 주어진 이야기(story.content)를 읽어주게 됩니다.
IconButton(
icon: Icon(Icons.play_arrow),
onPressed: () {
tts.speak(story.content);
},
),
정지 버튼이 눌리면, tts.stop()을 호출하여 음성 재생을 중지합니다.
IconButton(
icon: Icon(Icons.stop),
onPressed: () {
tts.stop();
},
),
아래코드는 이야기 데이터가 설정되어있지 않은 기본 tts 코드입니다.
import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Story Reader',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: StoryListScreen(),
);
}
}
class Story {
final String title;
final String content;
Story({required this.title, required this.content});
}
class StoryListScreen extends StatelessWidget {
final List<Story> stories = [
Story(title: "Story 1", content: "This is the content of story 1."),
Story(title: "Story 2", content: "This is the content of story 2."),
// 여기에 더 많은 이야기를 추가할 수 있습니다.
];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Readbook")),
body: ListView.builder(
itemCount: stories.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(stories[index].title),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
StoryDetailScreen(story: stories[index]),
),
);
},
);
},
),
);
}
}
class StoryDetailScreen extends StatelessWidget {
final Story story;
StoryDetailScreen({required this.story});
final TextToSpeech tts = TextToSpeech();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(story.title),
actions: [
IconButton(
icon: Icon(Icons.play_arrow),
onPressed: () {
tts.speak(story.content);
},
),
IconButton(
icon: Icon(Icons.stop),
onPressed: () {
tts.stop();
},
),
],
),
body: Padding(
padding: EdgeInsets.all(16.0),
child: Text(story.content),
),
);
}
}
class TextToSpeech {
FlutterTts flutterTts = FlutterTts();
Future speak(String text) async {
await flutterTts.speak(text);
}
Future stop() async {
await flutterTts.stop();
}
}