How to use the Ionic Native Media Plugin in Ionic

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!

Create a property “radio” where you put the instance of the MediaObject.

Hi Sujan, thanks for reaching out…

I’m fairly new to ionic, can you please illustrate how this should look in my home.ts file? I think I saw a similar method when I was researching, and I tried it but it didn’t work, perhaps there was an error somewhere there. Thanks for your time.

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

constructor(private media: Media) {}

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

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

try this

1 Like
export class SomeClass {

  mediaObject: MediaObject;

  constructor(private media: Media) {
    this.mediaObject = this.media.create(MEDIA_URI);
  }

  play() {
    this.mediaObject.play();
  }

  stop() {
    this.mediaObject.stop();
  }

Thanks Mohd-PH… your solution worked!

Hi Aaron,
Thanks for reaching out. However, your solution didn’t work. The solution is putting

this.mediaObject = this.media.create(MEDIA_URI); under the play function.

Thanks!

Nice to hear that :blush:

1 Like

It worked for me, thank you very much.

Does anyone know how to put autoplay with native ionic audio?