Flutter录音遇到的问题

862 阅读1分钟

使用的插件:just_audio

在使用过程中遇到一个问题,

encoder: AudioEncoder.pcm16bit

在于创建录音机时encoder这个参数。 我需要的是wav格式的录音文件。

如果我传递AudioEncoder.wav,录音什么的一切都正常,但是iOS设备上的录音文件在苹果设备上打开正常(iPhone iPad Mac),但是在安卓手机和windows电脑上显示是损坏的。 然后我通过慢慢测试发现iOS中使用AudioEncoder.pcm16bit这个值录出来的音频是正常的。但是这样安卓使用这个值录出来的音频是损坏的。。。。。 所以就要区分iOS和安卓设备进,分别使用不同的参数。于是就添加了以下代码:

AudioEncoder encoder;
if (Platform.isIOS){
  encoder = AudioEncoder.pcm16bit;
}else{
  encoder = AudioEncoder.wav;
}
  HeadsetEvent headsetPlugin = HeadsetEvent();
  HeadsetState? headsetEvent;
  beginRecord() async{
    if (await record.isRecording() == true){
      EasyLoading.showToast("正在录音");
      return;
    }
    String filePath = await _getFilePath();
    if (Platform.isIOS){
      encoder = AudioEncoder.pcm16bit;
    }else{
      encoder = AudioEncoder.wav;
    }
    if (await record.hasPermission()) {
      // Start recording
      await record.start(
        path: filePath,
        encoder: encoder, //这个根据你需要文件的格式选择不同的枚举, 具体选择看枚举说明或者百度
        bitRate: 256000, // 越高越好
        samplingRate: 48000, // 这个当然也是越高越好,但是会印象文件大小
      );
      int seconds = 0;
      setState(() {
        recordBtnText = "录音中0";
      });
      _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
        seconds +=1;
        setState(() {
          recordBtnText = "录音中$seconds";
        });
        print("seconds==$seconds");
      });

    }
  }

  Future<String> _getFilePath() async {
    /// 获取耳机链接状态,跟录音功能无关 插件:headset_connection_event
    headsetEvent = await headsetPlugin.getCurrentState;
    String headsetState = headsetEvent?.name ?? "";
// Check and request permission
    ///获取设备信息和时间戳.
    String dateStr = DateFormat('yyyyMMddHHmmss').format(DateTime.now());
    //获取手机的信息 插件 device_info_plus 具体方法:https://juejin.cn/post/7115267160074616869/
    DeviceEntity deviceInfo = await COPDDeviceInfo.deviceInfo;
    String deviceName = deviceInfo.brand! + "_" + deviceInfo.platform! + deviceInfo.systemVersion! + "_" + headsetState;
    //去除空格
    deviceName = deviceName.replaceAll(RegExp(r"\s*"), "");
    deviceName = Uri.encodeFull(deviceName);
    String fileName = deviceName+"_"+dateStr + ".wav" ;
    audioFileName = fileName;
    ///通过插件path_provider管理
    String filePath = await COPDFilePathManage.getRecordPath(fileName);
    print("dateStr=====$dateStr  fileName==$fileName, filePath==$filePath");
    return filePath;

  }
  endRecord() async{
    // Get the state of the recorder
    if (_timer!= null && _timer?.isActive == true){
      _timer?.cancel();
    }
    setState(() {
      recordBtnText = "开始录音";
    });
    ///获取录音文件路径
    String? path = await record.stop();
    ///判断文件是否存在
    if (await Directory(dirname(path!)).exists()) {
      print('路径存在');
    }else {
      print('路径不存在');
    }
    setState(() {
      //刷新页面展示路径
      audioPath = path;
    });

    // if (Platform.isIOS){
    //   changeFile();
    // }
    print('path==$path');
  }