Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Record audio using MediaPlugin and send to server using base64 - Ionic 2

In my Ionic 2 application. I have made a function which record audio and upload to server. I have used MediaPlugin and it can record fine, but when upload it and open it on server the file can't listen. I think it because type. So, How to convert MediaPlugin to correct base64 file for upload.

Service class for recording

import { Injectable } from '@angular/core';
import { MediaPlugin } from 'ionic-native';

export enum AudioRecorderState {
    Ready,
    Recording,
    Recorded
}

@Injectable()
export class AudioRecorder {
  mediaPlugin: MediaPlugin = null;
  state: AudioRecorderState = AudioRecorderState.Ready;

  getMediaPlugin(){
    return this.mediaPlugin;
  }

  preparedRecord(){
     this.mediaPlugin = new MediaPlugin('audio.mp3');
  }

  startRecording() {
    this.mediaPlugin.startRecord();
    this.state = AudioRecorderState.Recording;
  }

  stopRecording() {
    this.mediaPlugin.stopRecord();
    this.state = AudioRecorderState.Ready;
  }
}

Function in page class which call startRecording and stopRecording

 startRecording() {
    try {
      this.audioRecorder.preparedRecord();
      this.audioRecorder.startRecording();
    }
    catch (e) {
      this.showAlert('Failed');
    }
  }

  stopRecording() {
    try {
      this.audioRecorder.stopRecording();
      const media = this.audioRecorder.getMediaPlugin();

      this.base64Audio = "data:audio/mp3;base64," + media

      //Use base64Audio to Upload to Server...

    }
    catch (e) {
      this.showAlert('Could not stop recording.');
    }
  }
like image 771
Supon Avatar asked Apr 17 '26 20:04

Supon


1 Answers

The real problem is, the MediaPlugin does not create an mp3, that's only an appearance. So you can use wav, asd or anything, the MediaPlugin will play it correctly. However this plugin creates a file with aac (on android 3gp) extension. So you cannot play on the server because that thinks the file is an mp3 but it's not. I have the following issue when i tried to play it with html5 audio.

I do not know how your server works, but if like a html5 audio then you should convert your file to a supported extension (mp3, ogg, wav), or you should use another plugin.

like image 85
Hexiler Avatar answered Apr 20 '26 12:04

Hexiler