无法使用Ionic的媒体插件在音频文件中创建语音消息



我的应用程序中有聊天组件,我正在尝试添加发送语音消息(如WhatsApp(功能。我正在使用Ionic的媒体插件和MediaObject类型。该应用程序适用于Android和iOS。目前,我正在安卓上测试,没有任何运气!

我尝试了下面的代码来创建媒体对象并将录制的音频存储在其中。如果用户再次单击该按钮,我想停止录制。它正在工作,因为我在控制台上获取日志,但getDuration()返回 -1!

startRecording() {
if (!this.recording) {
      console.log('Started Recording');
      this.recording = true;
      this.fileName = Date.now();
      this.audio = this.media.create(`../../../../assets/chat/${this.fileName}.m4a`);
      this.audio.startRecord();
      this.listenToAudioEvents();
     } else {
      this.stopRecording();
    }
}
stopRecording() {
    this.audio.stopRecord();
    console.log(this.audio);
    this.recording = false;
    this.audioReady = true;
    this.audio.getDuration();
    console.log('Audio Duration: ' + this.audio.getDuration());
  }

我想在调用stopRecording()时停止录制并保留音频文件,以便我可以上传它。另外,我不确定文件实际上存储在Android或iOS上的位置。

基本上,问题是我保存生成的媒体文件的位置。首先,我需要使用Ionic Native的文件插件。然后在 iOS 的 File.tempDirectory 和 Android 的 File.externalDataDirectory 创建媒体文件:

if (this.platform.is('ios')) {
        await this.file.createFile(this.file.tempDirectory, this.fileName, true);
        this.filePath =  this.file.tempDirectory + this.fileName;
        this.audio = this.media.create(this.file.tempDirectory.replace(/^file:///, '') + this.fileName);
      } else if (this.platform.is('android')) {
        this.filePath = this.file.externalDataDirectory + this.fileName;
        this.audio = this.media.create(this.filePath);
      }
      this.audio.startRecord();

同样重要的是要注意适用于 iOS 的额外步骤,如页面底部所述。然后我能够像这样访问 blob:

this.file.readAsDataURL(this.filePath.replace(this.fileName, ''), this.fileName).then(blob => {
   console.log(blob);
}