Flutter:如何对Base64格式的音频文件进行编解码?
Flutter: How to encode and decode audio files in Base64 format?
我正在使用 Dialogflow 构建 ChatBot 应用程序,我想在我的应用程序中实现语音识别功能。如您所知,Dialogflow 为我们提供了 基于音频 检测意图的功能,但它只接受 base64 格式的音频。我的问题是我无法将音频文件编码为 Base64。我是 Flutter Development 的新手,所以如果我遗漏了什么或以错误的方式做,请告诉我。谢谢!
我试过这个方法,但它没有给我正确的输出:
Future<String> makeBase64(String path) async {
try {
if (!await fileExists(path)) return null;
File file = File(path);
file.openRead();
var contents = await file.readAsBytes();
var base64File = base64.encode(contents);
return base64File;
} catch (e) {
print(e.toString());
return null;
}
}
你可以这样做:
List<int> fileBytes = await file.readAsBytes();
String base64String = base64Encode(fileBytes);
转换后的字符串不包含 mimetype,因此您可能需要像这样包含
final fileString = 'data:audio/mp3;base64,$base64String';
我正在使用 Dialogflow 构建 ChatBot 应用程序,我想在我的应用程序中实现语音识别功能。如您所知,Dialogflow 为我们提供了 基于音频 检测意图的功能,但它只接受 base64 格式的音频。我的问题是我无法将音频文件编码为 Base64。我是 Flutter Development 的新手,所以如果我遗漏了什么或以错误的方式做,请告诉我。谢谢!
我试过这个方法,但它没有给我正确的输出:
Future<String> makeBase64(String path) async {
try {
if (!await fileExists(path)) return null;
File file = File(path);
file.openRead();
var contents = await file.readAsBytes();
var base64File = base64.encode(contents);
return base64File;
} catch (e) {
print(e.toString());
return null;
}
}
你可以这样做:
List<int> fileBytes = await file.readAsBytes();
String base64String = base64Encode(fileBytes);
转换后的字符串不包含 mimetype,因此您可能需要像这样包含
final fileString = 'data:audio/mp3;base64,$base64String';