0.1.0 • Published 6 years ago

@nstudio/nativescript-audio-recorder v0.1.0

Weekly downloads
2
License
Apache-2.0
Repository
github
Last release
6 years ago

Installation

tns plugin add @nstudio/nativescript-audio-recorder

Usage

import {
  AudioRecorder,
  AudioRecorderOptions
} from '@nstudio/nativescript-audio-recorder';
import { File, knownFolders } from 'tns-core-modules/file-system';
import { isAndroid } from 'tns-core-modules/platform';

export class SomeClassInYourProject {
  private _recorder: AudioRecorder;

  constructor() {
    this._recorder = new AudioRecorder();
  }

  public startRecordingAudio() {
    if (!AudioRecorder.DEVICE_CAN_RECORD()) {
      console.log('crud, this device cannot record audio');
      return;
    }

    const audioFolder = knownFolders.currentApp().getFolder('audio');

    let androidFormat;
    let androidEncoder;
    if (isAndroid) {
      androidFormat = android.media.MediaRecorder.OutputFormat.MPEG_4;
      androidEncoder = android.media.MediaRecorder.AudioEncoder.AAC;
    }

    const recorderOptions: AudioRecorderOptions = {
      filename: `${audioFolder.path}/recording.${isAndroid ? 'm4a' : 'caf'}`,

      format: androidFormat,

      encoder: androidEncoder,

      metering: true,

      infoCallback: infoObject => {
        console.log(JSON.stringify(infoObject));
      },

      errorCallback: errorObject => {
        console.log(JSON.stringify(errorObject));
      }
    };

    this._recorder
      .start(recorderOptions)
      .then(result => {
        console.log('recording has started', result);
      })
      .catch(err => {
        console.log('oh no, something is wrong and recording did not start');
      });
  }

  public pauseRecording() {
    this._recorder
      .pause()
      .then(result => {
        console.log('recording has been paused');
      })
      .catch(err => {
        console.log('recording could not be paused');
      });
  }

  public async stopRecording() {
    const stopResult = await this._recorder.stop().catch(err => {
      console.log('oh no recording did not stop correctly');
    });
    if (stopResult) {
      console.log('recording stopped successfully.');
    }
  }

  public getFile() {
    try {
      const audioFolder = knownFolders.currentApp().getFolder('audio');
      const recordedFile = audioFolder.getFile(
        `recording.${isAndroid ? 'm4a' : 'caf'}`
      );
      console.log(JSON.stringify(recordedFile));
      console.log('recording exists: ' + File.exists(recordedFile.path));
      this.recordedAudioFile = recordedFile.path;
    } catch (ex) {
      console.log(ex);
    }
  }

  public async disposeRecorder() {
    const disposeResult = await this._recorder.dispose().catch(err => {
      dialogs.alert({
        message: `Dispose Error: ${err}`,
        okButtonText: 'Okay'
      });
    });
    console.log('disposeResult', disposeResult);
    this._recorder = new AudioRecorder();
  }
}

API

MethodDescription
start(options: AudioRecorderOptions):Promise<boolean>Starts recording audio from the device. Permissions are required to record. The plugin attempts to request needed permissions.
stop():Promise<boolean>Stops the recording.
pause():Promise<boolean>Pauses the recording.
resume():Promise<boolean>Resumes the recording.
dispose():Promise<boolean>Disposes of the audio recorder. This will release resources and null out the internal recorder. So it's best to create a new instance of the AudioRecorder after if you want to record again.

Interfaces

AudioRecorderOptions

interface AudioRecorderOptions {
  /**
   * Gets or sets the recorded file name.
   */
  filename: string;

  /**
   * Sets the source for recording ***ANDROID ONLY for now ***
   */
  source?: any;

  /**
   * Gets or set the max duration of the recording session.
   */
  maxDuration?: number;

  /**
   * Enable metering. Off by default.
   */
  metering?: boolean;

  /**
   * Format
   */
  format?: any;

  /**
   * Channels
   */
  channels?: any;

  /**
   * Sampling rate
   */
  sampleRate?: any;

  /**
   * Bit rate
   */
  bitRate?: any;

  /**
   * Encoding
   */
  encoder?: any;

  /**
   * Gets or sets the callback when an error occurs with the media recorder.
   * @returns {Object} An object containing the native values for the error callback.
   */
  errorCallback?: Function;

  /**
   * Gets or sets the callback to be invoked to communicate some info and/or warning about the media or its playback.
   * @returns {Object} An object containing the native values for the info callback.
   */
  infoCallback?: Function;
}

License

Apache License Version 2.0, January 2004