Flutter:如何以Base64格式编码和解码音频文件? [英] Flutter: How to encode and decode audio files in Base64 format?

查看:132
本文介绍了Flutter:如何以Base64格式编码和解码音频文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Dialogflow 构建ChatBot应用,并且我想在我的应用中实现语音识别功能.如您所知,Dialogflow为我们提供了一项功能,基于音频检测意图,但它仅接受base64形式的音频.对我来说,问题是我无法将音频文件编码为Base64.我是Flutter Development的新手,所以如果万一我遗漏了某些东西或做错了方法,请告诉我.谢谢!

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

推荐答案

您可以执行以下操作:

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

转换后的字符串不包含mimetype,因此您可能需要这样包含

The converted string doesn't include mimetype, so you might need to include like this

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

这篇关于Flutter:如何以Base64格式编码和解码音频文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆