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

时间:2019-07-11 23:09:21

标签: javascript angular typescript cordova ionic4

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

我尝试了下面的代码来创建MediaObject并将录制的音频存储在其中。如果用户再次单击该按钮,我想停止录制。之所以起作用,是因为我在控制台上获得了日志,但是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上的实际存储位置。

1 个答案:

答案 0 :(得分:0)

基本上,问题是我保存生成的媒体文件的位置。首先,我需要使用Ionic Native的File插件。然后在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();

注意页面底部here概述的iOS的额外步骤也很重要。然后我就可以像这样访问Blob:

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