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

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

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

text_to_speech_macos 是 macOS 平台上 text_to_speech 插件的实现。

使用

添加依赖

此包已被认可,这意味着你只需在 pubspec.yaml 文件中添加 text_to_speech 作为依赖项。当你依赖 package:text_to_speech 时,它会自动包含在你的应用中。

这表示在你的 pubspec.yaml 文件中应该添加如下内容:

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

如果你只想使用 macOS 版本的包,可以添加 text_to_speech_macos 作为依赖项:

dependencies:
  ...
  text_to_speech_macos: <text_to_speech_macos_version>
  ...

有关更多使用细节,请参阅 这里

完整示例

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

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:text_to_speech_platform_interface/text_to_speech_platform.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';

  TextToSpeechPlatform tts = TextToSpeechPlatform.instance;

  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 示例'),
        ),
        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_macos的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

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


当然,下面是一个关于如何在Flutter项目中使用text_to_speech_macos插件来实现文本转语音功能的代码案例。这个插件允许你在macOS平台上将文本转换为语音。

首先,确保你的Flutter项目已经设置好,并且你已经添加了text_to_speech及其macOS平台的依赖。

  1. 添加依赖

在你的pubspec.yaml文件中添加以下依赖:

dependencies:
  flutter:
    sdk: flutter
  text_to_speech: ^5.0.0 # 请检查最新版本号

同时,在pubspec.yaml文件中添加macOS平台的依赖:

dependency_overrides:
  text_to_speech_macos:
    git:
      url: https://github.com/justmaier/flutter_text_to_speech.git
      path: text_to_speech_macos

注意:由于插件版本和路径可能会更新,请确保使用最新版本或正确路径。

  1. 配置iOS和macOS平台

ios/Runner/Info.plistmacos/Runner/Info.plist中添加必要的权限请求(虽然主要是iOS需要,但macOS也建议检查)。

<key>NSMicrophoneUsageDescription</key>
<string>We need your permission to use the microphone for text to speech</string>
  1. 实现文本转语音功能

在你的Flutter项目中,创建一个新的Dart文件(例如text_to_speech_service.dart)来实现文本转语音功能:

import 'package:flutter/services.dart';
import 'package:text_to_speech/text_to_speech.dart';

class TextToSpeechService {
  late TextToSpeech _tts;

  TextToSpeechService() {
    _tts = TextToSpeech();

    _tts.setLanguage("en-US").then((result) {
      if (result) {
        print("Language set to en-US");
      } else {
        print("Language setting failed");
      }
    });

    _tts.setPitch(1.0);
    _tts.setSpeechRate(1.0);
    _tts.setVolume(1.0);
  }

  Future<void> speak(String text) async {
    bool result = await _tts.speak(text);
    if (result) {
      print("Text to speech success");
    } else {
      print("Text to speech failed");
    }
  }

  Future<bool> isLanguageAvailable(String languageCode) async {
    return await _tts.isLanguageAvailable(languageCode);
  }

  Future<void> stop() async {
    await _tts.stop();
  }
}
  1. 使用文本转语音服务

在你的主页面或其他组件中使用这个服务:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late TextToSpeechService _ttsService;

  @override
  void initState() {
    super.initState();
    _ttsService = TextToSpeechService();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Text to Speech Demo'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            String text = "Hello, this is a text to speech demo.";
            await _ttsService.speak(text);
          },
          child: Text('Speak'),
        ),
      ),
    );
  }
}

这段代码展示了如何在Flutter项目中集成和使用text_to_speech_macos插件来实现文本转语音功能。确保在实际项目中根据需要进行错误处理和用户体验优化。

回到顶部