【发布时间】:2020-11-16 15:33:29
【问题描述】:
我编写了一个函数,它接收 2 个字符串(语句、问题)并使用 Google TTS 大声朗读。
我正在使用flutter_tts: ^1.3.0 包并尝试使用setVoice 方法将扬声器的声音更改为google voices 支持的声音之一:
这是我的代码:
Future _speak(statement, question) async {
flutterTts.setLanguage("cmn-CN");
flutterTts.setVoice("cmn-CN-Standard-B");
flutterTts.setSpeechRate(0.7);
await flutterTts.speak(statement + question);
}
该函数在读取文本时起作用,但我在 setVoice 方法上收到错误消息:
D/TTS (12461): Voice name not found: cmn-CN-Standard-B
有人可以帮忙吗?谢谢!
更新
我意识到我没有使用 google TTS 服务,所以我这样做是为了实现男性和女性的声音。这段代码现在对我有用。
import 'dart:typed_data';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:audioplayers/audioplayers.dart';
var _apikey = "AIzaSyDWx34PZW0hjSpwExBo5bwrENvyRkLisBE";
AudioPlayer audioPlayer = AudioPlayer();
const String femalevoice = "cmn-CN-Standard-A";
const String malevoice = "cmn-CN-Standard-B";
Future<http.Response> texttospeech(String text, String voicetype) {
String url =
"https://texttospeech.googleapis.com/v1beta1/text:synthesize?key=$_apikey";
var body = json.encode({
"audioConfig": {"audioEncoding": "LINEAR16", "pitch": 0, "speakingRate": 1},
"input": {"text": text},
"voice": {"languageCode": "cmn-CN", "name": voicetype}
});
var response =
http.post(url, headers: {"Content-type": "application/json"}, body: body);
return response;
}
// Play male voice
playmalevoice(String text) async {
var response = await texttospeech(text, malevoice);
var jsonData = jsonDecode(response.body);
String audioBase64 = jsonData['audioContent'];
Uint8List bytes = base64Decode(audioBase64);
String dir = (await getApplicationDocumentsDirectory()).path;
File file =
File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + ".mp3");
await file.writeAsBytes(bytes);
int result = await audioPlayer.play(file.path);
audioPlayer.setPlaybackRate(playbackRate: 0.7);
audioPlayer.setVolume(1);
if (result == 1) {
// success
}
}
// play female voice
playfemalevoice(String text) async {
var response = await texttospeech(text, femalevoice);
var jsonData = jsonDecode(response.body);
String audioBase64 = jsonData['audioContent'];
Uint8List bytes = base64Decode(audioBase64);
String dir = (await getApplicationDocumentsDirectory()).path;
File file =
File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + ".mp3");
await file.writeAsBytes(bytes);
int result = await audioPlayer.play(file.path);
audioPlayer.setPlaybackRate(playbackRate: 0.7);
audioPlayer.setVolume(1);
if (result == 1) {
// success
}
}
【问题讨论】:
-
我试过 await flutterTts.setVolume(volume);等待 flutterTts.setSpeechRate(rate);等待颤振Tts.setPitch(音高); Map
参考 = {'voice': "cmn-CN-Standard-B"};等待flutterTts.setVoice(参考);但是 setVoices 并没有变成女声
标签: flutter dart text-to-speech