Search code examples
cordovaionic2cordova-media-plugin

ionic 2.1.14 MediaPlugin methods undefined


I can't seem to place method on property that has MediaPlugin import. It tells me it is undefined. I want to keep the file link in the class and execute wavplay() from my home.html.

Here is my code:

//ionic start blank --v2    
//home.ts

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

    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })

    export class HomePage {

      constructor(public navCtrl: NavController) {}

      wavfile = new MediaPlugin('file:///android_asset/www/mp3/testwav.wav');

      wavplay() {
        this.wavfile.play(); // .play() undefined
      }
      mp3play() {
        new MediaPlugin('file:///android_asset/www/mp3/testmp3.mp3').play(); //But this works
      }
    }

Any solution? I'm testing my app on android 6.0.1


Solution

  • If you want to keep the file name in the class, use a property like this

    //ionic start blank --v2    
    //home.ts
    
        import { Component } from '@angular/core';
        import { NavController } from 'ionic-angular';
        import { MediaPlugin } from 'ionic-native';
    
        @Component({
          selector: 'page-home',
          templateUrl: 'home.html'
        })
    
        export class HomePage {
    
          private wavfile: any;  // <- Declare the class property
    
          constructor(public navCtrl: NavController) {
            // Initialize the property
            this.wavfile = new MediaPlugin('file:///android_asset/www/mp3/testwav.wav');
          }
    
          public wavplay(): void {
            this.wavfile.play();  // <- use it
          }
        }