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

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

本包目前处于开发阶段。

piper_tts 是一个用于跨平台使用 Piper 神经语音模型的 Flutter 文本到语音插件。

示例代码

以下是使用 piper_tts 插件的基本示例代码。该示例展示了如何在 Flutter 应用程序中实现文本转语音功能。

import 'package:flutter/material.dart';
import 'package:piper_tts/piper_tts.dart';
import 'package:audioplayers/audioplayers.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Piper TTS Example'),
        ),
        body: const TTSPage(),
      ),
    );
  }
}

class TTSPage extends StatefulWidget {
  const TTSPage({super.key});

  [@override](/user/override)
  State<TTSPage> createState() => _TTSPageState();
}

class _TTSPageState extends State<TTSPage> {
  final TextEditingController _controller = TextEditingController();
  final AudioPlayer _audioPlayer = AudioPlayer();
  bool _isPlaying = false;

  void _generateAndPlaySpeech() async {
    if (_controller.text.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text('请输入一些文本')));
      return;
    }

    try {
      // 生成语音
      final file = await Piper.generateSpeech(_controller.text);

      // 将文件路径转换为DeviceFileSource以供播放方法使用
      final source = DeviceFileSource(file.path);

      // 播放生成的音频
      await _audioPlayer.play(source);
      setState(() {
        _isPlaying = true;
      });

      // 监听音频播放器的状态,当音频播放完毕时重置播放状态
      _audioPlayer.onPlayerComplete.listen((event) async {
        await Future.delayed(const Duration(milliseconds: 500));

        setState(() {
          _isPlaying = false;
        });
      });
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(e.toString())));
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Container(
      padding: const EdgeInsets.all(20.0),
      child: Column(
        children: [
          TextField(
            controller: _controller,
            decoration: const InputDecoration(
              hintText: '输入要朗读的文本',
            ),
          ),
          const SizedBox(height: 20),
          ElevatedButton(
            onPressed: _isPlaying ? null : _generateAndPlaySpeech,
            child: Text(_isPlaying ? '正在播放...' : '生成语音'),
          ),
        ],
      ),
    );
  }
}

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

1 回复

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


piper_tts 是一个用于文本转语音(TTS)的插件,适用于 Flutter 应用程序。它基于 piper 引擎,支持多语言和多种语音。以下是如何在 Flutter 项目中使用 piper_tts 插件的基本指南。

1. 添加依赖项

首先,你需要在 pubspec.yaml 文件中添加 piper_tts 插件的依赖项。

dependencies:
  flutter:
    sdk: flutter
  piper_tts: ^0.1.0  # 使用最新版本

然后运行 flutter pub get 来获取依赖项。

2. 安装语音模型

piper_tts 需要下载语音模型才能正常工作。你可以在 Piper 的 GitHub 仓库 找到支持的语音模型。

下载你需要的语音模型文件(通常是 .onnx.json 文件),并将它们放在你的项目中的 assets 目录下。

例如:

assets/
  models/
    en-US-amy-medium.onnx
    en-US-amy-medium.json

然后在 pubspec.yaml 文件中声明这些资源:

flutter:
  assets:
    - assets/models/en-US-amy-medium.onnx
    - assets/models/en-US-amy-medium.json

3. 初始化 piper_tts

在你的 Dart 代码中,初始化 piper_tts 并加载语音模型。

import 'package:piper_tts/piper_tts.dart';

class TextToSpeechService {
  PiperTts? _piperTts;

  Future<void> initTts() async {
    _piperTts = PiperTts();

    // 加载语音模型
    await _piperTts!.loadModel(
      modelPath: 'assets/models/en-US-amy-medium.onnx',
      configPath: 'assets/models/en-US-amy-medium.json',
    );
  }

  Future<void> speak(String text) async {
    if (_piperTts != null) {
      await _piperTts!.speak(text);
    }
  }
}

4. 使用 piper_tts

在你的应用中使用 TextToSpeechService 来将文本转换为语音。

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  final ttsService = TextToSpeechService();
  await ttsService.initTts();

  runApp(MyApp(ttsService: ttsService));
}

class MyApp extends StatelessWidget {
  final TextToSpeechService ttsService;

  MyApp({required this.ttsService});

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Piper TTS Example')),
        body: Center(
          child: ElevatedButton(
            onPressed: () async {
              await ttsService.speak('Hello, world!');
            },
            child: Text('Speak'),
          ),
        ),
      ),
    );
  }
}
回到顶部