【问题标题】:Unable to create voice message in audio file using Ionic's Media plugin无法使用 Ionic 的媒体插件在音频文件中创建语音消息
【发布时间】:2019-12-17 18:30:48
【问题描述】:

我的应用中有聊天组件,我正在尝试添加发送语音消息(如 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 上的哪个位置。

【问题讨论】:

  • 所以我认为很多这些方法应该是异步的,并且会接受一个回调函数,其参数应该是录音?无论如何,您是否尝试在此插件的 github 上寻找示例?

标签: javascript angular typescript cordova ionic4


【解决方案1】:

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

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 的额外步骤也很重要,如页面底部的here 所述。然后我就可以像这样访问 blob:

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

【讨论】:

  • 谢谢你。弄明白这件事真是太烦人了!
猜你喜欢
  • 1970-01-01
  • 2017-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-04
  • 1970-01-01
相关资源
最近更新 更多