Flutter实现tts语音播报

目录

引言

添加flutter_tts依赖

设置语言和发音人

macOS

Android

iOS

说话、停止、获取语言、设置语言、设置语音速率、获取声音、设置声音、设置音量、设置音高、是否语言可用、设置共享实例

监听平台

封装代码

使用案例


引言

随着移动应用的不断发展,用户对应用的交互体验要求越来越高。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'),
              ),
             
            ],
          ),
        ),
      ),
    );
  }
}
相关推荐
MavenTalk1 天前
前端技术选型之uniapp
android·前端·flutter·ios·uni-app·前端开发
sunly_2 天前
Flutter:启动屏逻辑处理01:修改默认APP启动图标
flutter
sunly_2 天前
Flutter:启动屏逻辑处理02:启动页
android·javascript·flutter
Alex_z08972 天前
flutter gradle版本更新到8.9
flutter
那年星空2 天前
Flutter 设计模式全面解析:抽象工厂
flutter·设计模式·架构
林北芒大果2 天前
【Flutter】搭建Flutter开发环境,安卓开发
android·flutter
SunshineBrother2 天前
Flutter求职、面试20+面试官总结:Dart篇
android·前端·flutter
李新_3 天前
一文聊聊Flutter多业务混合工程实践
android·flutter
sunly_3 天前
Flutter:flutter_screenutil屏幕适配
前端·javascript·flutter