直接使用 Flutter 进行http请求不用插件,以下是请求微软语音合成后生成音频文件
// 请求微软文字转语音
static Future<String> postMicrosoftMusciFile(String text) async {
String authorization = AzureAudioManager().appKey;
String region = AzureAudioManager().appRegion;
String ssmlContent = '''
<speak version='1.0' xmlns='http://www.w3.org/2001/10/synthesis' xml:lang='zh-CN'>
<voice name='zh-CN-XiaoxiaoNeural'>
$text
</voice>
</speak>
''';
String url =
"https://$region.tts.speech.microsoft.com/cognitiveservices/v1";
Map<String, String> headers = {
"Authorization": authorization, // 请确保正确设置了Bearer令牌
"Content-Type": "application/ssml+xml",
"X-Microsoft-OutputFormat":
"audio-16khz-32kbitrate-mono-mp3", // 输出模型
};
Dio dio = Dio(); // 创建Dio实例
BaseOptions options = BaseOptions(
// baseUrl: baseUrl,
receiveTimeout: const Duration(seconds: 10),
sendTimeout: const Duration(seconds: 15),
connectTimeout: const Duration(seconds: 15),
responseType: ResponseType.json,
headers: headers);
dio.options = options;
options.responseType = ResponseType.bytes;
final response = await dio.post(
url,
data: ssmlContent,
);
// 请求成功,返回音频数据 (字节数组)
if (response.statusCode == 200) {
Directory appDocDir = await getApplicationDocumentsDirectory();
String appDocPath = appDocDir.path;
// 创建文件
File file = File('$appDocPath/music.mp3');
// 将下载的内容写入文件
await file.writeAsBytes(response.data);
LoggerUtils.logDebugPrint(file.path);
return file.path;
} else {
SmartDialog.showToast("voice error,code=: ${response.statusCode}");
return '';
}
}
播放可以直接使用flutter_sound
这个库就行了
// 播放语音文字
Future<void> playAiTTS(
{required bool allowBlue,
required String text,
double banlace = 0,
required VoidCallback finish,
int playType = 0}) async {
var path = "";
try {
path = await Api.aiTTs(text: text, playType: playType);
} catch (e) {
Logger().w(e);
finish();
throw Exception(e);
}
await playMP3(
allowBlue: allowBlue, path: path, banlace: banlace, finish: finish);
}