How to use the Ionic Native Media Plugin in Ionic 2 / 3

541 Views Asked by At

I've been struggling for hours trying to implement the media plugin in my ionic 3 app. I had a look at the Ionic docs as well as the plugin docs but both seem to have a different way of implementing it. The only way I can get it to work is through the following, but I think this is the wrong way and the code just looks dirty!

home.ts:

import { Media, MediaObject } from '@ionic-native/media';

constructor(private media: Media) {}

playAudio() { 
const radio: MediaObject = this.media.create('MY_URL');
radio.play();
}

stopAudio() { 
const radio: MediaObject = this.media.create('MY_URL');
radio.stop();
}

home.html:

<ion-content...>

<button ion-button color="secondary" (click)="playAudio()">Play</button>

<button ion-button color="secondary" (click)="playAudio()">Play</button>

I'm having to duplicate the stream url twice (both in the play and once again in the stop function) just to get it to work - I know this is not the right way, someone please assist. Thanks!

2

There are 2 best solutions below

0
On
import { Media, MediaObject } from '@ionic-native/media';

export class MyComponent {
radio: MediaObject

constructor(private media: Media) {}


playAudio() { 
this.radio = this.media.create('MY_URL');
this.radio.play();
  }

stopAudio() { 
this.radio.stop();
  }
}
3
On

Why dont you try to instantiate the radio property in the constructor?

import { Media, MediaObject } from '@ionic-native/media';

export class MyComponent {
  radio: MediaObject

  constructor(private media: Media) {
    this.radio = this.media.create('MY_URL');
  }

  playAudio() { 
    this.radio.play();
  }

  stopAudio() { 
    this.radio.stop();
  }
}