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

2,563

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';
Share:
2,563
mechanic
Author by

mechanic

Updated on December 17, 2022

Comments

  • mechanic
    mechanic over 1 year

    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;
        }
      }
    
  • mechanic
    mechanic about 4 years
    No, but I guess the encoded output that I'm getting is incomplete, because when I try to decode the output it gives me an incompatible audio file. I'm using this site for decoding: Link
  • mechanic
    mechanic about 4 years
    It worked! Thanks a lot @xion. I was making a mistake by printing the output in the debug console and then using it for decoding without knowing the fact that debug console do not provide us the whole string if the string is quite large.