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. Cordova Media plugin provides the ability to record and playback audio files on a device. Cordova File plugin implements a File API allowing read/write access to files residing on the device. Using those plugins make Ionic Angular sound playback app easy to build.

Table of Contents:

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:

  1. Node.js (Recommended Version)
  2. Ionic 3
  3. Angular 5
  4. 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 ionic@latest
sudo npm i cordova

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


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

 

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 cordova-plugin-media and cordova-plugin-file.

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 these imports of Ionic Native Media and File.

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
]


Implementing Media Plugin

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

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 UI of sound playback that contain the list of the audio file, play, and stop button.

<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>


Run and Test Ionic Angular App on The Device

Because we are using Ionic 3 Cordova Native Media plugin, we must run the Ionic Angular 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.

We know that building beautifully designed Ionic apps from scratch can be frustrating and very time-consuming. Check Ionic 4 - Full Starter App and save development and design time. Android, iOS, and PWA, 100+ Screens and Components, the most complete and advance Ionic Template.

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

Thanks!

Loading…