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

强颜欢笑 提交于 2020-12-30 02:45:13

问题


I'm building a ChatBot app using Dialogflow and I want to implement Voice Recognition feature in my app. 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. The problem for me is that I'm unable to encode the audio file into 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. 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;
    }
  }

回答1:


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

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


来源:https://stackoverflow.com/questions/60202639/flutter-how-to-encode-and-decode-audio-files-in-base64-format

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!