Skip to content

Instantly share code, notes, and snippets.

@AmitMY
Created August 13, 2017 15:00
Show Gist options
  • Save AmitMY/5cef18954d21eaa747401018636345a1 to your computer and use it in GitHub Desktop.
Save AmitMY/5cef18954d21eaa747401018636345a1 to your computer and use it in GitHub Desktop.
Ionic record audio (error)
import { IonicPage, ModalController, ToastController } from 'ionic-angular';
import { Component } from '@angular/core';
import { Media, MediaObject } from '@ionic-native/media';
import { File } from '@ionic-native/file';
import { UserProvider } from '../../providers/user/user';
@IonicPage({ segment: 'index' })
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
didLeave: boolean = false;
isRecording: boolean = false;
currentRecording: MediaObject;
constructor(private media: Media,
private user: UserProvider,
private file: File,
private modalCtrl: ModalController,
private toastCtrl: ToastController) {
}
ionViewCanEnter() {
return this.user.isAuthenticated();
}
ionViewWillLeave() {
this.didLeave = true;
this._stopRecording();
}
private getFileDirectory() {
return this.file.tempDirectory || this.file.dataDirectory;
}
private getFileName() {
return 'file.mp3';
}
private getFilePath() {
return this.getFileDirectory() + this.getFileName();
}
async startRecording() {
try {
console.debug('createFile', this.getFileDirectory(), this.getFileName());
await this.file.createFile(this.getFileDirectory(), this.getFileName(), true);
console.debug('createMedia', this.getFilePath());
this.currentRecording = this.media.create(this.getFilePath());
this.currentRecording.onSuccess.subscribe(() => {
this.currentRecording.play();
console.log(this.currentRecording.getDuration()); // -1
if (!this.didLeave) {
this.modalCtrl.create('AddAudioModal', { file: this.getFilePath() }).present();
}
});
this.currentRecording.onError.subscribe((err) => console.error(err));
this.currentRecording.startRecord();
this.isRecording = true;
} catch (err) {
console.error(err);
this.toastCtrl.create({
message: err,
duration: 3000
}).present();
}
}
private _stopRecording() {
this.currentRecording.stopRecord();
this.isRecording = false;
}
stopRecording() {
this._stopRecording();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment