Search code examples
androidionic-frameworkionic4media

Low quality audio file when trying to record using media and file in ionic


I’m trying to record audio in android using media ( https://ionicframework.com/docs/native/media ) but the recorded audio has very low quality with noise when I play it back, Here is the link of the question in ionic forum: https://forum.ionicframework.com/t/low-quality-audio-file-when-trying-to-record-using-media-and-file/191952

Here is my code:

import { Component } from '@angular/core';
import { Media, MediaObject } from '@ionic-native/media/ngx';
import { File } from '@ionic-native/file/ngx';
import { Platform } from '@ionic/angular';

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


  filePath: string;
  recordedAudio: MediaObject;
  recording: Boolean = false;
  constructor(
    private media: Media,
    private file: File,
    public platform: Platform
  ) { }

  startRecord() {
    if (this.platform.is('android')) {

      console.log('Android');
      console.log(this.file.externalRootDirectory);
      this.filePath = this.file.externalRootDirectory + 'my_file.3gp';
      console.log(this.filePath)
      this.file.createFile(this.file.externalRootDirectory, 'my_file.3gp', true).then(() => {
        this.recordedAudio = this.media.create(this.file.externalRootDirectory.replace(/^file:\/\//, '') + 'my_file.3gp');
        this.recordedAudio.startRecord();
        window.setTimeout(() => this.recordedAudio.stopRecord(), 50000);
      });
    }
    this.recording = true;
  }

  stopRecord() {
    if (this.platform.is('android')) {
      this.recordedAudio.stopRecord();
      this.recordedAudio.release();
    }

  }

  playSelectedTrack() {
    // use AudioProvider to control selected track 
    if (this.platform.is('android')) {
      this.recordedAudio.play();
    }
  }

  pauseSelectedTrack() {
    // use AudioProvider to control selected track 
    if (this.platform.is('android')) {
      this.recordedAudio.pause();
    }
  }
}

Solution

  • This might be because of audio encoding. 3gp always sounds bad. Try m4a or mp3. m4a works in few android phones and has better quality.

    This is from Cordova Github Repo: Android devices record audio in AAC ADTS file format. The specified file should end with a .aac extension.

    You can also use Media-Capture to record audio.

    Github Repo: Media-Capture