Using MediaPlugin to stream music, how can I keep music playing when switching out of app or locking phone?

MediaPlugin works great for streaming, however the music fades out when switching out of the app or enabling the lock screen.

How can I keep the music playing in the background?

Saw this: https://github.com/katzer/cordova-plugin-background-mode

But it looks like Apple Store isn’t to fond of it’s use.

Also, is there anyway to access music controls on the lock screen? The MusicControls plugin looks like it does it but only for Android and Windows, doesn’t look like there’s an iOS counterpart.

Here’s my code:

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


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

export class HomePage {

	radio: MediaPlugin;
	playing: boolean;

  constructor(public navCtrl: NavController, platform: Platform) {

    platform.ready().then(() => {
      // Okay, so the platform is ready and our plugins are available.
      	// Here you can do any higher level native things you might need.
    	this.radio = new MediaPlugin("http://relay.publicdomainproject.org/classical.aac.m3u");

    });
  }

  radioPlay() {
  	this.radio.play();
  	this.playing = true;
  }

  radioPause() {
  	this.radio.pause();
  	this.playing = false;
  }

}
1 Like

I just completed an app and ran into the same problem, here is how I solved it.

To allow the audio to play in the background you to do two things. First, you need to set the background mode - audio to on within the Xcode capabilities. Second, you need your AppDelegate.m file in the platforms - classes folder to look like this.

#import "AppDelegate.h"
#import "MainViewController.h"
#import <AVFoundation/AVFoundation.h>
@implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    BOOL ok;
    NSError *setCategoryError = nil;
    ok = [audioSession setCategory:AVAudioSessionCategoryPlayback error:&setCategoryError];
    self.viewController = [[MainViewController alloc] init];
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
@end

To get the player controls on the lock screen and notifications area you need this plugin: GitHub - shi11/RemoteControls: cordova 3 plugin for interacting with ios7 remote controls and metadata

To accurately portray the play/pause icon make sure your app actually suspends the audio and not just pauses it.

Let me know if you run into any issues implementing these.

6 Likes

This is great, thank you!

First two parts worked perfectly, able to continue playing music when switching out of application and while screen is locked.

Couple questions:

  1. Tried to install RemoteControls, received this error when executing ionic plugin add com.rd11.remote-controls

Error: Registry returned 404 for GET on https://registry.npmjs.org/com.rd11.remote-controls

  1. What was your solution for Android?

Thanks again!

Do

ionic plugin add https://github.com/shi11/RemoteControls

For Android I used the MusicControls plugin

Cool, that worked.

How did you go about implementing it with TypeScript?

You don’t need to do anything special besides for using ‘let’ and changing it to

window['remoteControls'].updateMetas((success)=>{
}, (fail)=>{
}, params);
1 Like

Okay, got it to work sort of… is there a hook for the pause/play button?

My constructor looks like this:

platform.ready().then(() => {

	this.radio = new MediaPlugin("http://relay.publicdomainproject.org/classical.aac.m3u");

	this.radio.init.then(() => {
		  console.log('Playback Finished');
		}, (err) => {
		  console.log('somthing went wrong! error code: ' + err.code + ' message: ' + err.message);
		});

		let artist = "Daft Punk";
		let title = "One More Time";
		let album = "Discovery";
		let image = "path_within_documents_storage OR url_starting_with_http_or_https";
		let duration = 1;
		let elapsedTime = 1;

		let params = [artist, title, album, image, duration, elapsedTime];
		window['remoteControls'].updateMetas((success)=>{
		}, (fail)=>{
		}, params);
});

But still not able to see the artist/title on the lock screen, it just shows up blank.

Got the hooks to work by adding the following to the constructor. Needed to declare event:any as TypeScript wouldn’t compile otherwise.

document.addEventListener('remote-event', (event:any) => {

    switch(event.remoteEvent.subtype) {
    	case "play":
    		console.log("PLAY");
    		this.radioPlay();
    		break;
    	case "pause":
    		console.log("PAUSE");
    		this.radioPause();
    		break;
    }
});

Still can’t get

window['remoteControls'].updateMetas((success)=>{
}, (fail)=>{
}, params);

to work though, did you place it in the constructor? On the play event?

I also noticed that the lock screen controls go away after you press pause, is there anyway to keep them up during a pause?

Try with an image from a url. I couldn’t get the local file image to work.

Ah, that was it. For reference, is there anyway to not show an image or does that value always have to be filled? I tried setting it as a null or “” and it ended up giving me the same issue

Curious, were you able to get AAC files to work in Android? Mp3s work, but AACs are giving me an issue.

For Android, I only use OGG files because I think they give the best quality for the size. If they worked on Apple I would use them there also but they don’t.

What did you end up using for your iOS streams?

I used AAC though none of my audio is streamed. This is my app for reference https://play.google.com/store/apps/details?id=net.sleeporbit

I got the Android controls working in Android 6.0 and 7.1 but they don’t show up in 5.0?

P.S. Great app! Love how you broke the mold of a traditional looking app.

Thanks for the comment
I haven’t seen any issues on android 5 that I know of.

What was your solution for setting the volume? Using the Media Plugin I’m trying to use the setVolume method but it doesn’t seem to be working.

I use the Web Audio API

1 Like

Hello,

I have added https://github.com/shi11/RemoteControls plugin, everything works great BUT not the progress bar, it’s not stop when is in Pause state. How can I make it stops when music paused?

Plus, if we click pause/play audio in app, the notification area buttons don’t update. It always is in Play mode.

Can you kindly give a help?

I’m using Ionic 2 + Cordova MediaPlugin.

Thanks in advance.

To get the button to change you need to stop the audio instead of just pausing. Seems to be the only way to get it to work properly.

1 Like