繁体   English   中英

使用媒体捕获cordova插件在ionic 4应用程序中录制音频

[英]Recording audio inside ionic 4 app using media-capture cordova plugin

我正在尝试使用媒体捕获cordova插件在ionic 4应用程序中录制音频,但问题是当我点击录制按钮时,它会打开一个外部录音机应用程序并录制音频,然后我可以在我的应用程序中播放它。 我想在不打开外部录音机的情况下在我的应用程序中录制音频。 请帮忙!

这是我的 home.page.html:

<ion-header>
  <ion-toolbar>
    <ion-title>
      Audio Testing App
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="ion-padding">
    <ion-button color="primary" (click)="record()">Record</ion-button>

    <ion-list>
      <ion-item-sliding *ngFor="let f of files">
        <ion-item (click)="openFile(f)">
          <ion-icon name="mic" slot="start"></ion-icon>

          <ion-label class="ion-text-wrap">
            {{ f.name }}
            <p>{{ f.fullPath }}</p>
          </ion-label>
        </ion-item>

        <ion-item-options side="start">
          <ion-item-option (click)="deleteFile(f)" color="danger">
            <ion-icon name="trash" slot="icon-only"></ion-icon>
          </ion-item-option>
        </ion-item-options>
      </ion-item-sliding>
    </ion-list>
  </div>
</ion-content>

home.page.ts 文件:

import { Component, OnInit } from '@angular/core';
import { NativeAudio } from '@ionic-native/native-audio/ngx';
import { MediaCapture, MediaFile, CaptureError } from '@ionic-native/media-capture/ngx';
import { File, FileEntry } from '@ionic-native/File/ngx';
import { Platform } from '@ionic/angular';
import { Media, MediaObject } from '@ionic-native/media/ngx';

const MEDIA_FOLDER_NAME = 'audio_app_media';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit {
  files = [];

  constructor(private nativeAudio: NativeAudio,
    private mediaCapture: MediaCapture,
    private file: File,
    private media: Media,
    private plt: Platform) { }

  ngOnInit() {
    this.plt.ready().then(() => {
      let path = this.file.dataDirectory;
      this.file.checkDir(path, MEDIA_FOLDER_NAME).then(
        () => {
          this.loadFiles();
        },
        err => {
          this.file.createDir(path, MEDIA_FOLDER_NAME, false);
        }
      );
    });
  }

  loadFiles() {
    this.file.listDir(this.file.dataDirectory, MEDIA_FOLDER_NAME).then(
      res => {
        this.files = res;
      },
      err => console.log('error loading files: ', err)
    );
  }

  record() {
    this.mediaCapture.captureAudio().then(
      (data: MediaFile[]) => {
        if (data.length > 0) {
          this.copyFileToLocalDir(data[0].fullPath);
        }
      },
      (err: CaptureError) => console.error(err)
    );
  }

  openFile(f: FileEntry) {
    const path = f.nativeURL.replace(/^file:\/\//, '');
    const audioFile: MediaObject = this.media.create(path);
    audioFile.play();
  }

  deleteFile(f: FileEntry) {
    const path = f.nativeURL.substr(0, f.nativeURL.lastIndexOf('/') + 1);
    this.file.removeFile(path, f.name).then(() => {
      this.loadFiles();
    }, err => console.log('error remove: ', err));
  }

  copyFileToLocalDir(fullPath) {
    let myPath = fullPath;
    // Make sure we copy from the right location
    if (fullPath.indexOf('file://') < 0) {
      myPath = 'file://' + fullPath;
    }

    const ext = myPath.split('.').pop();
    const d = Date.now();
    const newName = `${d}.${ext}`;

    const name = myPath.substr(myPath.lastIndexOf('/') + 1);
    const copyFrom = myPath.substr(0, myPath.lastIndexOf('/') + 1);
    const copyTo = this.file.dataDirectory + MEDIA_FOLDER_NAME;

    this.file.copyFile(copyFrom, name, copyTo, newName).then(
      success => {
        this.loadFiles();
      },
      error => {
        console.log('error: ', error);
      }
    );
  }

}

这是该应用程序的屏幕截图: 图 1:主页

在此处输入图片说明

图 2:外部录制,点击录制按钮会打开

(不想去这里,而是直接在我的应用程序内记录)

在此处输入图片说明

无需担心。 您还可以在应用程序内录制音频。

captureAudio(
){
  try {
    let fileName =
    'record' +
    new Date().getDate() +
    new Date().getMonth() +
    new Date().getFullYear() +
    new Date().getHours() +
    new Date().getMinutes() +
    new Date().getSeconds();
    // let filePath = '';
    if (this.platform.is('ios')) {
      fileName = fileName + '.m4a';
      this.audioPath = this.file.documentsDirectory + fileName;
      this.audio = this.media.create(this.audioPath.replace(/file:\/\//g, ''));
    } else if (this.platform.is('android')) {
      fileName = fileName + '.mp3';
      this.audioPath = this.file.externalDataDirectory + fileName;
      this.audio = this.media.create(this.audioPath.replace(/file:\/\//g, ''));
    }
    this.audio.startRecord();
    this.isAudioRecording = true;
  } catch (error) {
    console.log(error);
  }
}


stopAudio() {
  this.audio.stopRecord();
  this.isAudioRecording = false;
}

playAudio() {
try {
  this.audio = this.media.create(this.audioPath);
  this.audio.play();
  this.audio.setVolume(0.8);
} catch (error) {
  console.log(error);
}
}

不要忘记添加

<application android:requestLegacyExternalStorage="true" />

在 confix.xml 文件中

您应该尝试cordova-plugin-media

此代码不适用于 android 级别 10 或 11 设备...请提供更多解决方案

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM