Flutter文本转语音插件text_to_speech_web的使用

发布于 1周前 作者 sinazl 来自 Flutter

Flutter文本转语音插件text_to_speech_web的使用

介绍

text_to_speech_webtext_to_speech 插件在Web平台上的实现。通过这个插件,您可以在Flutter Web应用中实现文本转语音的功能。

使用方法

添加依赖

要使用该插件,首先需要在您的 pubspec.yaml 文件中添加依赖:

dependencies:    
  ...    
  text_to_speech: <text_to_speech_version>     
  ...    

或者单独添加 text_to_speech_web 插件:

dependencies:    
  ...    
  text_to_speech_web: <text_to_speech_web_version>     
  ...    

完整示例Demo

以下是一个完整的示例代码,展示了如何在Flutter Web应用中使用 text_to_speech_web 插件。

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';

import 'package:text_to_speech_web/text_to_speech_web.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final String defaultLanguage = 'en-US';

  TextToSpeechWeb tts = TextToSpeechWeb();

  String text = '';
  double volume = 1; // 范围:0-1
  double rate = 1.0; // 范围:0-2
  double pitch = 1.0; // 范围:0-2

  String? language;
  String? languageCode;
  List<String> languages = [];
  List<String> languageCodes = [];
  String? voice;

  TextEditingController textEditingController = TextEditingController();

  [@override](/user/override)
  void initState() {
    super.initState();
    textEditingController.text = text;
    WidgetsBinding.instance?.addPostFrameCallback((_) {
      initLanguages();
    });
  }

  Future<void> initLanguages() async {
    /// 填充语言代码(例如 en-US)
    languageCodes = await tts.getLanguages();

    /// 填充显示的语言(例如 English)
    List<String>? displayLanguages = await tts.getDisplayLanguages();

    if (displayLanguages == null) {
      return;
    }

    languages.clear();
    for (dynamic lang in displayLanguages) {
      languages.add(lang as String);
    }

    /// 获取默认语言
    final String? defaultLangCode = await tts.getDefaultLanguage();
    if (defaultLangCode != null && languageCodes.contains(defaultLangCode)) {
      languageCode = defaultLangCode;
    } else {
      languageCode = defaultLanguage;
    }
    language = await tts.getDisplayLanguageByCode(languageCode!);

    /// 获取声音
    voice = await getVoiceByLang(languageCode!);

    if (mounted) {
      setState(() {});
    }
  }

  Future<String?> getVoiceByLang(String lang) async {
    List<String>? voices = await tts.getVoiceByLang(languageCode!);
    if (voices != null && voices.isNotEmpty) {
      return voices.first;
    }
    return null;
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Text-to-Speech Example'),
        ),
        body: SingleChildScrollView(
          child: Padding(
            padding: const EdgeInsets.all(20.0),
            child: Center(
              child: Column(
                children: <Widget>[
                  TextField(
                    controller: textEditingController,
                    maxLines: 5,
                    decoration: InputDecoration(
                        border: OutlineInputBorder(),
                        hintText: '输入一些文本...'),
                    onChanged: (String newText) {
                      setState(() {
                        text = newText;
                      });
                    },
                  ),
                  Row(
                    children: <Widget>[
                      Text('音量'),
                      Expanded(
                        child: Slider(
                          value: volume,
                          min: 0,
                          max: 1,
                          label: volume.round().toString(),
                          onChanged: (double value) {
                            initLanguages();
                            setState(() {
                              volume = value;
                            });
                          },
                        ),
                      ),
                      Text('(${volume.toStringAsFixed(2)})'),
                    ],
                  ),
                  Row(
                    children: <Widget>[
                      Text('速率'),
                      Expanded(
                        child: Slider(
                          value: rate,
                          min: 0,
                          max: 2,
                          label: rate.round().toString(),
                          onChanged: (double value) {
                            setState(() {
                              rate = value;
                            });
                          },
                        ),
                      ),
                      Text('(${rate.toStringAsFixed(2)})'),
                    ],
                  ),
                  Row(
                    children: <Widget>[
                      Text('音调'),
                      Expanded(
                        child: Slider(
                          value: pitch,
                          min: 0,
                          max: 2,
                          label: pitch.round().toString(),
                          onChanged: (double value) {
                            setState(() {
                              pitch = value;
                            });
                          },
                        ),
                      ),
                      Text('(${pitch.toStringAsFixed(2)})'),
                    ],
                  ),
                  Row(
                    children: <Widget>[
                      Text('语言'),
                      SizedBox(
                        width: 20,
                      ),
                      DropdownButton<String>(
                        value: language,
                        icon: const Icon(Icons.arrow_downward),
                        iconSize: 24,
                        elevation: 16,
                        style: const TextStyle(color: Colors.deepPurple),
                        underline: Container(
                          height: 2,
                          color: Colors.deepPurpleAccent,
                        ),
                        onChanged: (String? newValue) async {
                          languageCode =
                              await tts.getLanguageCodeByName(newValue!);
                          voice = await getVoiceByLang(languageCode!);
                          setState(() {
                            language = newValue;
                          });
                        },
                        items: languages
                            .map<DropdownMenuItem<String>>((String value) {
                          return DropdownMenuItem<String>(
                            value: value,
                            child: Text(value),
                          );
                        }).toList(),
                      ),
                    ],
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Row(
                    children: <Widget>[
                      Text('声音'),
                      SizedBox(
                        width: 20,
                      ),
                      Text('${voice ?? '-'}'),
                    ],
                  ),
                  SizedBox(
                    height: 20,
                  ),
                  Row(
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          padding: EdgeInsets.only(right: 10),
                          child: ElevatedButton(
                            child: Text('停止'),
                            onPressed: () {
                              tts.stop();
                            },
                          ),
                        ),
                      ),
                      if (supportPause)
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.only(right: 10),
                            child: ElevatedButton(
                              child: Text('暂停'),
                              onPressed: () {
                                tts.pause();
                              },
                            ),
                          ),
                        ),
                      if (supportResume)
                        Expanded(
                          child: Container(
                            padding: EdgeInsets.only(right: 10),
                            child: ElevatedButton(
                              child: Text('恢复'),
                              onPressed: () {
                                tts.resume();
                              },
                            ),
                          ),
                        ),
                      Expanded(
                          child: Container(
                        child: ElevatedButton(
                          child: Text('朗读'),
                          onPressed: () {
                            speak();
                          },
                        ),
                      ))
                    ],
                  )
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  bool get supportPause => defaultTargetPlatform != TargetPlatform.android;

  bool get supportResume => defaultTargetPlatform != TargetPlatform.android;

  void speak() {
    tts.setVolume(volume);
    tts.setRate(rate);
    if (languageCode != null) {
      tts.setLanguage(languageCode!);
    }
    tts.setPitch(pitch);
    tts.speak(text);
  }
}

更多关于Flutter文本转语音插件text_to_speech_web的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter文本转语音插件text_to_speech_web的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中集成和使用text_to_speech_web插件来实现文本转语音功能的示例代码。这个插件专门用于在Web平台上实现文本转语音功能。

1. 添加依赖

首先,你需要在pubspec.yaml文件中添加text_to_speech_web依赖:

dependencies:
  flutter:
    sdk: flutter
  text_to_speech_web: ^x.y.z  # 替换为最新版本号

2. 导入插件

在你的Dart文件中(通常是main.dart或者某个具体功能的页面),导入插件:

import 'package:text_to_speech_web/text_to_speech_web.dart';

3. 初始化插件

在需要使用文本转语音功能的地方,初始化插件并进行配置。通常这会在某个页面或组件的initState方法中进行:

import 'package:flutter/material.dart';
import 'package:text_to_speech_web/text_to_speech_web.dart';

class TextToSpeechPage extends StatefulWidget {
  @override
  _TextToSpeechPageState createState() => _TextToSpeechPageState();
}

class _TextToSpeechPageState extends State<TextToSpeechPage> {
  late TextToSpeechWeb tts;

  @override
  void initState() {
    super.initState();
    tts = TextToSpeechWeb();
    tts.initialize().then((value) {
      if (value) {
        print("Text-to-Speech initialized successfully");
      } else {
        print("Failed to initialize Text-to-Speech");
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Text to Speech Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Hello, World!',
              style: TextStyle(fontSize: 24),
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () => _speak("Hello, this is a text to speech example."),
              child: Text('Speak'),
            ),
          ],
        ),
      ),
    );
  }

  void _speak(String text) {
    tts.speak(text);
  }

  @override
  void dispose() {
    tts.dispose();
    super.dispose();
  }
}

4. 运行应用

确保你已经正确配置了Flutter开发环境,并且Flutter CLI已经指向了正确的Web目标(通常使用flutter run -d chrome来运行Web应用)。

5. 完整代码结构

确保你的项目结构类似于以下:

your_flutter_project/
├── android/
├── ios/
├── lib/
│   ├── main.dart
│   └── (其他页面或组件)
├── pubspec.yaml
└── (其他配置文件)

main.dart中,你可以简单地导入并展示上述TextToSpeechPage

import 'package:flutter/material.dart';
import 'path_to_your_text_to_speech_page.dart';  // 例如 'lib/text_to_speech_page.dart'

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Text to Speech Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: TextToSpeechPage(),
    );
  }
}

通过上述步骤,你应该能够在Flutter Web应用中成功集成并使用text_to_speech_web插件来实现文本转语音功能。记得在实际项目中处理错误和异常情况,并根据需要调整UI和逻辑。

回到顶部