Record and Play Sound in Ionic 3 Angular 5 Cordova Mobile App

by Didin J. on Nov 24, 2017 Record and Play Sound in Ionic 3 Angular 5 Cordova Mobile App

Step by step tutorial on how to record and play sound or audio in Ionic 3 Angular 5 Cordova Mobile App with the working example

Step by step tutorial on how to record and play sound or audio in Ionic 3 Angular 5 Cordova Mobile App with the working example. The scenario of this tutorial just a record button, list of recorded sound/audio and play button on each sound/audio item. The result of the user interface should be like this.

Record and Play Sound in Ionic 3 Angular 5 Cordova Mobile App - Result App

The following tools, framework, and modules are required for this tutorial:

- Node.js (Recommended Version)
- Ionic 3
- Angular 5
- Cordova

We assume that you have installed the recommended version of Node.js. Now, update or install Ionic 3 latest version. Open the terminal (MAC/Linux) or Node command line (Windows) then type this command.

sudo npm i -D -E [email protected]
sudo npm i cordova

You can exclude `sudo` if using Node command line on Windows.


1. Create a New Ionic 3 Angular 5 App

On the terminal or Node.js command line type this command to create a new Ionic 3, Angular 5 and Cordova App after go to your projects folder.

ionic start ionic-sound blank

Go to your newly created project folder by type this command.

cd ./ionic-sound

For tutorial sanitation, run the app on the browser then type this command.

ionic serve -l

And you will see this page in the default browser.

Record and Play Sound in Ionic 3 Angular 5 Cordova Mobile App - Ionic 3 Blank Page

 

2. Add Ionic 3 Cordova Native Media and File Plugin

To make an app for recording and playing sound, simple add Ionic 3 Cordova Native Media and File plugin. On the terminal type this command to install it.

ionic cordova plugin add cordova-plugin-media
npm install --save @ionic-native/media
ionic cordova plugin add cordova-plugin-file
npm install --save @ionic-native/file

Next, open and edit `src/app/app.module.ts` then add this import.

import { Media } from '@ionic-native/media';
import { File } from '@ionic-native/file';

Then declare `Media` to `@NgModule` providers.

providers: [
  StatusBar,
  SplashScreen,
  {provide: ErrorHandler, useClass: IonicErrorHandler},
  Media,
  File
]


3. Implementing Media Plugin

As you see in the first paragraph of this tutorial, you find a single page with record button and playlist of recorded audio/sound file. Next, modify `src/pages/home/home.ts` then add this imports.

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

Inject to the constructor.

constructor(public navCtrl: NavController,
  private media: Media,
  private file: File,
  public platform: Platform) {}

Declares the required variables before the constructor.

recording: boolean = false;
filePath: string;
fileName: string;
audio: MediaObject;
audioList: any[] = [];

Add function for getting the list of audio files.

getAudioList() {
  if(localStorage.getItem("audiolist")) {
    this.audioList = JSON.parse(localStorage.getItem("audiolist"));
    console.log(this.audioList);
  }
}

Call it from `ionViewWillEnter`.

ionViewWillEnter() {
  this.getAudioList();
}

Add function for start recording.

startRecord() {
  if (this.platform.is('ios')) {
    this.fileName = 'record'+new Date().getDate()+new Date().getMonth()+new Date().getFullYear()+new Date().getHours()+new Date().getMinutes()+new Date().getSeconds()+'.3gp';
    this.filePath = this.file.documentsDirectory.replace(/file:\/\//g, '') + this.fileName;
    this.audio = this.media.create(this.filePath);
  } else if (this.platform.is('android')) {
    this.fileName = 'record'+new Date().getDate()+new Date().getMonth()+new Date().getFullYear()+new Date().getHours()+new Date().getMinutes()+new Date().getSeconds()+'.3gp';
    this.filePath = this.file.externalDataDirectory.replace(/file:\/\//g, '') + this.fileName;
    this.audio = this.media.create(this.filePath);
  }
  this.audio.startRecord();
  this.recording = true;
}

Add function for stop recording.

stopRecord() {
  this.audio.stopRecord();
  let data = { filename: this.fileName };
  this.audioList.push(data);
  localStorage.setItem("audiolist", JSON.stringify(this.audioList));
  this.recording = false;
  this.getAudioList();
}

Add function for play audio/sound file.

playAudio(file,idx) {
  if (this.platform.is('ios')) {
    this.filePath = this.file.documentsDirectory.replace(/file:\/\//g, '') + file;
    this.audio = this.media.create(this.filePath);
  } else if (this.platform.is('android')) {
    this.filePath = this.file.externalDataDirectory.replace(/file:\/\//g, '') + file;
    this.audio = this.media.create(this.filePath);
  }
  this.audio.play();
  this.audio.setVolume(0.8);
}

Next, for the view just open and edit `src/pages/home/home.html` then replace all tags with this.

<ion-header>
  <ion-navbar>
    <ion-title>
      Sound Recorder & Player
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-card>
    <ion-card-content>
      <ion-card-title>
        <button ion-button primary (click)="stopRecord()" *ngIf="recording"><ion-icon name="mic-off"></ion-icon>&nbsp;&nbsp;Stop Record</button>
        <button ion-button primary (click)="startRecord()" *ngIf="!recording"><ion-icon name="mic"></ion-icon>&nbsp;&nbsp;Start Record</button>
      </ion-card-title>
    </ion-card-content>
  </ion-card>
  <ion-list>
    <ion-item *ngFor="let audio of audioList; index as i;">
      <p>{{audio.filename}}</p>
      <button ion-button clear item-end large (click)="playAudio(audio.filename, i)"><ion-icon name="play"></ion-icon></button>
    </ion-item>
  </ion-list>
</ion-content>


4. Run and Test on The Device

Because we are using Ionic 3 Cordova Native Media plugin, we must run the app on the Android or iOS device. Before running the app, we have to re-install the platform by typing this command.

ionic cordova platform rm android
ionic cordova platform add android
ionic cordova platform rm ios
ionic cordova platform add ios

Now, run the Ionic 3 Angular 5 Cordova Audio Recorder & Player app on the Android or iOS device. Make sure, you have connected your device to your Computer.

ionic cordova run android

or

ionic cordova run ios

You can try record and play recorded audio file on your device. You can find the working source code on our GitHub.

That just the basic. If you need more deep learning about Ionic, Angular, and Typescript, you can find the following books:

Or take the following course:

Thanks!

The following resources might be useful for you:

Loading…