Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

base64

flutter

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;
    }
  }
like image 216
mechanic Avatar asked Mar 02 '23 19:03

mechanic


1 Answers

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';
like image 177
xion Avatar answered Mar 05 '23 09:03

xion