目录
说话、停止、获取语言、设置语言、设置语音速率、获取声音、设置声音、设置音量、设置音高、是否语言可用、设置共享实例
引言
随着移动应用的不断发展,用户对应用的交互体验要求越来越高。TTS(Text-to-Speech,文本转语音)技术可以让应用读出文本内容,从而提升用户体验,特别是对于视障用户或需要多任务处理的场景非常有用。本文将详细介绍如何在 Flutter 应用中使用 flutter_tts
库实现 TTS 功能。
添加flutter_tts依赖
在 pubspec.yaml
文件中加
Dart
flutter_tts: ^4.0.2
然后执行
flutter pub get
设置语言和发音人
- 使用
setLanguage
方法设置语言
Dart
await flutterTts.setLanguage("zh-CN"); // 设置为中文
- 使用
setVoice
方法选择不同的发音人:
Dart
await flutterTts.setVoice("female"); // 选择女性发音人
macOS
OSX version: 10.15
Android
将文件中的最低 Android sdk 版本更改为 21(或更高)android/app/build.gradle
。
`minSdkVersion 21`
更新 Kotlin Gradle 插件版本
将 Kotlin Gradle 插件的版本更改为1.9.10
。
如果你的项目是使用 3.19 之前的 Flutter 版本创建的,请转到android/build.gradle
文件并更新ext.kotlin_version
:
`ext.kotlin_version = '1.9.10'`
否则,请转到android/settings.gradle
并更新插件的版本org.jetbrains.kotlin.android
:
`id "org.jetbrains.kotlin.android" version "1.9.10" apply false`
针对 Android 11 且使用文本转语音功能的应用应在其清单元素TextToSpeech.Engine.INTENT_ACTION_TTS_SERVICE 中声明。queries
<queries>`
`<intent>`
`<action android:name="android.intent.action.TTS_SERVICE" />`
`</intent>`
`</queries>`
`
iOS
设置共享音频实例(仅限 iOS)
Dart
await flutterTts.setSharedInstance(true);
使用可选模式设置音频类别和选项(仅限 iOS)。以下设置允许背景音乐和应用内音频会话同时继续
Dart
await flutterTts.setIosAudioCategory(IosTextToSpeechAudioCategory.ambient,
[
IosTextToSpeechAudioCategoryOptions.allowBluetooth,
IosTextToSpeechAudioCategoryOptions.allowBluetoothA2DP,
IosTextToSpeechAudioCategoryOptions.mixWithOthers
],
IosTextToSpeechAudioMode.voicePrompt
);
等待发言完成。
Dart
await flutterTts.awaitSpeakCompletion(true);
等待合成文件完成。
Dart
await flutterTts.awaitSynthCompletion(true);
说话、停止、获取语言、设置语言、设置语音速率、获取声音、设置声音、设置音量、设置音高、是否语言可用、设置共享实例
Dart
Future _speak() async{
var result = await flutterTts.speak("Hello World");
if (result == 1) setState(() => ttsState = TtsState.playing);
}
Future _stop() async{
var result = await flutterTts.stop();
if (result == 1) setState(() => ttsState = TtsState.stopped);
}
List<dynamic> languages = await flutterTts.getLanguages;
await flutterTts.setLanguage("en-US");
await flutterTts.setSpeechRate(1.0);
await flutterTts.setVolume(1.0);
await flutterTts.setPitch(1.0);
await flutterTts.isLanguageAvailable("en-US");
// iOS, Android and Web only
//see the "Pausing on Android" section for more info
await flutterTts.pause();
// iOS, macOS, and Android only
// The last parameter is an optional boolean value for isFullPath (defaults to false)
await flutterTts.synthesizeToFile("Hello World", Platform.isAndroid ? "tts.wav" : "tts.caf", false);
// Each voice is a Map containing at least these keys: name, locale
// - Windows (UWP voices) only: gender, identifier
// - iOS, macOS only: quality, gender, identifier
// - Android only: quality, latency, network_required, features
List<Map> voices = await flutterTts.getVoices;
await flutterTts.setVoice({"name": "Karen", "locale": "en-AU"});
// iOS, macOS only
await flutterTts.setVoice({"identifier": "com.apple.voice.compact.en-AU.Karen"});
// iOS only
await flutterTts.setSharedInstance(true);
// Android only
await flutterTts.speak("Hello World", focus: true);
await flutterTts.setSilence(2);
await flutterTts.getEngines;
await flutterTts.getDefaultVoice;
await flutterTts.isLanguageInstalled("en-AU");
await flutterTts.areLanguagesInstalled(["en-AU", "en-US"]);
await flutterTts.setQueueMode(1);
await flutterTts.getMaxSpeechInputLength;
await flutterTts.setAudioAttributesForNavigation();
监听平台
Dart
flutterTts.setStartHandler(() {
setState(() {
ttsState = TtsState.playing;
});
});
flutterTts.setCompletionHandler(() {
setState(() {
ttsState = TtsState.stopped;
});
});
flutterTts.setProgressHandler((String text, int startOffset, int endOffset, String word) {
setState(() {
_currentWord = word;
});
});
flutterTts.setErrorHandler((msg) {
setState(() {
ttsState = TtsState.stopped;
});
});
flutterTts.setCancelHandler((msg) {
setState(() {
ttsState = TtsState.stopped;
});
});
// Android, iOS and Web
flutterTts.setPauseHandler((msg) {
setState(() {
ttsState = TtsState.paused;
});
});
flutterTts.setContinueHandler((msg) {
setState(() {
ttsState = TtsState.continued;
});
});
封装代码
Dart
// tts_service.dart
import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
class TtsService {
final FlutterTts flutterTts = FlutterTts();
Future<void> initTts() async {
var availableLanguages = await flutterTts.getLanguages;
print("Available languages: $availableLanguages");
var isLanguageAvailable = await flutterTts.isLanguageAvailable("zh-CN");
print("Is zh-CN available: $isLanguageAvailable");
if (isLanguageAvailable) {
await flutterTts.setLanguage("zh-CN"); // 设置语言为中文
await flutterTts.setPitch(1.0); // 设置音调
await flutterTts.setSpeechRate(1); // 设置语速
} else {
print("Language zh-CN is not available");
}
}
Future<void> speak(String text) async {
await initTts(); // 确保 TTS 服务已经初始化
await flutterTts.speak(text); // 播放语音
}
}
使用案例
Dart
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
final TtsService ttsService = TtsService();
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Flutter TTS Example')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () async { await ttsService.speak("嘿嘿嘿哈哈哈"); },
child: const Text('Speak'),
),
],
),
),
),
);
}
}