简体   繁体   English

Flutter:如何对 Base64 格式的音频文件进行编码和解码?

[英]Flutter: How to encode and decode audio files in Base64 format?

I'm building a ChatBot app using Dialogflow and I want to implement Voice Recognition feature in my app.我正在使用Dialogflow构建 ChatBot 应用程序,并且我想在我的应用程序中实现语音识别功能。 As you know Dialogflow provide us a feature to detect intent on the basis of audio but it only accepts audio in the form of base64.如您所知,Dialogflow 为我们提供了基于音频检测意图的功能,但它仅接受 base64 形式的音频。 The problem for me is that I'm unable to encode the audio file into Base64.我的问题是我无法将音频文件编码为 Base64。 I'm new to Flutter Development so if in case I'm missing something or doing it in a wrong way then please let me know.我是 Flutter 开发的新手,所以如果我遗漏了什么或以错误的方式做,请告诉我。 Thanks!谢谢!

I've tried this method but it's not giving me the proper output:我试过这种方法,但它没有给我正确的输出:

  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;
    }
  }

You could do this:你可以这样做:

List<int> fileBytes = await file.readAsBytes();
String base64String = base64Encode(fileBytes);

The converted string doesn't include mimetype, so you might need to include like this转换后的字符串不包含 mimetype,因此您可能需要像这样包含

final fileString = 'data:audio/mp3;base64,$base64String';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM