Giter Club home page Giter Club logo

capacitor-music-controls-plugin-new's Introduction

Capacitor Music Controls Plugin New

An update to Cordova Music Controls plugin to support Capacitor 3

Music controls for Capacitor applications. Display a 'media' notification with play/pause, previous, next buttons, allowing the user to control the play. Handles headset events (plug, unplug, headset button) on Android.

work in progress

this integration is a work in progress. currently, most controls work as expected. there are some questions around supplying images on iOS.

PRs for rounding out issues and improving the plugin are welcome.

Supported platforms

  • Android
  • iOS

Installation

  • Current release npm install https://github.com/gokadzev/capacitor-music-controls-plugin-new.git

iOS

Run: npx cap sync ios

Android

After you install the plugin, locate your MainActivity.java (can be found in /android/app/src/main/java/path/to/my/app/MainActivity.java)

import this path:

import com.gokadzev.capacitormusiccontrols.CapacitorMusicControls;

add class inside bridge activity: add(CapacitorMusicControls.class);

example:

import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
import com.gokadzev.capacitormusiccontrols.CapacitorMusicControls;

public class MainActivity extends BridgeActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        registerPlugin(CapacitorMusicControls.class);
    }
}

add to build.gradle :

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

Finally, run: npx cap sync android

Importing the Plugin

At the top of your file import Capacitor Plugins and this extract this plugin

import { CapacitorMusicControls } from "capacitor-music-controls-plugin-new";

Methods

  • Create the media controls:
CapacitorMusicControls.create({
	track       : 'Time is Running Out',		// optional, default : ''
	artist      : 'Muse',						// optional, default : ''
	album       : 'Absolution',     // optional, default: ''
 	cover       : 'albums/absolution.jpg',		// optional, default : nothing
	// cover can be a local path (use fullpath 'file:///storage/emulated/...', or only 'my_image.jpg' if my_image.jpg is in the www folder of your app)
	//			 or a remote url ('http://...', 'https://...', 'ftp://...')

	// hide previous/next/close buttons:
	hasPrev   : false,		// show previous button, optional, default: true
	hasNext   : false,		// show next button, optional, default: true
	hasClose  : true,		// show close button, optional, default: false


	duration : 0, // (in seconds) required


	// iOS only, optional
	elapsed : 10, // optional, default: 0
  	hasSkipForward : true, //optional, default: false. true value overrides hasNext.
  	hasSkipBackward : true, //optional, default: false. true value overrides hasPrev.
  	skipForwardInterval : 15, //optional. default: 15.
	skipBackwardInterval : 15, //optional. default: 15.
	hasScrubbing : false, //optional. default to false. Enable scrubbing from control center progress bar 

    // Android only, optional
    isPlaying   : true,							// optional, default : true
    dismissable : true,							// optional, default : false
	// text displayed in the status bar when the notification (and the ticker) are updated
	ticker	  : 'Now playing "Time is Running Out"',
	//All icons default to their built-in android equivalents
	//The supplied drawable name, e.g. 'media_play', is the name of a drawable found under android/res/drawable* folders
	playIcon: 'media_play',
	pauseIcon: 'media_pause',
	prevIcon: 'media_prev',
	nextIcon: 'media_next',
	closeIcon: 'media_close',
	notificationIcon: 'notification',
	iconsColor: 0xffffffff // controller icons color, default: white (url for more colors: https://developer.android.com/reference/android/graphics/Color#constants_1 ) 

}).then(()=>{
	// TODO
})
.catch(e=>{
	console.log(e);
});
  • Update whether the music is playing true/false, as well as the time elapsed (seconds)
//Update only playing status

CapacitorMusicControls.updateIsPlaying({ isPlaying: true }).then(()=>{
	// TODO
})
.catch(e=>{
	console.log(e);
});

//or just
 
CapacitorMusicControls.updateIsPlaying({ isPlaying: true });


//Update as playing status as elapsed time

CapacitorMusicControls.updateState({
	elapsed: timeElapsed, // affects iOS Only
	isPlaying: true // affects Android only
}).then(()=>{
	// TODO
})
.catch(e=>{
	console.log(e);
});
  • Listen for events and pass them to your handler function
CapacitorMusicControls.addListener('controlsNotification', (info: any) => {
    console.log('controlsNotification was fired');
    console.log(info);
    handleControlsEvent(info);
});
  • Example event handler
function handleControlsEvent(action) {

	console.log("hello from handleControlsEvent")
	const message = action.message;

	console.log("message: " + message)

	switch(message) {
		case 'music-controls-next':
			// next
			break;
		case 'music-controls-previous':
			// previous
			break;
		case 'music-controls-pause':
			// paused
			break;
		case 'music-controls-play':
			// resumed
			break;
		case 'music-controls-destroy':
			// controls were destroyed
			break;

		// External controls (iOS only)
		case 'music-controls-toggle-play-pause' :
			// do something
			break;
		case 'music-controls-skip-to':
			// do something
			break;
		case 'music-controls-skip-forward':
			// Do something
			break;
		case 'music-controls-skip-backward':
			// Do something
			break;

		// Headset events (Android only)
		// All media button events are listed below
		case 'music-controls-media-button' :
			// Do something
			break;
		case 'music-controls-headset-unplugged':
			// Do something
			break;
		case 'music-controls-headset-plugged':
			// Do something
			break;
		default:
			break;
	}
}

credits & contributions

Original plugin by: wako-app (https://github.com/wako-app/)

Contributors:

capacitor-music-controls-plugin-new's People

Contributors

4v3ngr avatar gokadzev avatar jumbay avatar leo-jnesis avatar patrickjquinn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

capacitor-music-controls-plugin-new's Issues

Remote (BT headphones e.g) controls not working on Android

Looks like the Bluetooth control events for pause, play, skip song etc are not firing on Android.

For the pause play events i'd suggest trying to request audio focus when the events are fired, and for the skip song (i.e if I double tab play pause on most headphones it triggers the next event on most app), it's likely this was never implemented in the original project.

I've done some experimentation around the above so let me know if you need pointing in the right direction ๐Ÿ‘

Capacitor 4

Hi, i am trying this plugin with capacitor 4.
I can install it but when i add the code to the MainActivity.java it gives me the problem:

Cannot resolve symbol gokadzev.

How can i add this dependency?

WebContentsDelegate::CheckMediaAccessPermission: Not supported.

Hello, the app crashes on my Samsung A52S when I call the Plugin. In Android Studio it says

WebContentsDelegate::CheckMediaAccessPermission: Not supported.

After adding <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" /> to AndroidManifest it says:

E/Capacitor: Serious error executing plugin
    java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at com.getcapacitor.PluginHandle.invoke(PluginHandle.java:121)
        at com.getcapacitor.Bridge.lambda$callPluginMethod$0$com-getcapacitor-Bridge(Bridge.java:598)
        at com.getcapacitor.Bridge$$ExternalSyntheticLambda5.run(Unknown Source:8)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loopOnce(Looper.java:226)
        at android.os.Looper.loop(Looper.java:313)
        at android.os.HandlerThread.run(HandlerThread.java:67)
     Caused by: java.lang.IllegalArgumentException: de.btcecho.app: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
    Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
        at android.app.PendingIntent.checkFlags(PendingIntent.java:382)
        at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:673)
        at android.app.PendingIntent.getBroadcast(PendingIntent.java:660)
        at com.gokadzev.capacitormusiccontrols.MusicControlsNotification.createBuilder(MusicControlsNotification.java:209)
        at com.gokadzev.capacitormusiccontrols.MusicControlsNotification.updateNotification(MusicControlsNotification.java:81)
        at com.gokadzev.capacitormusiccontrols.CapacitorMusicControls.updateMetadata(CapacitorMusicControls.java:224)
        at com.gokadzev.capacitormusiccontrols.CapacitorMusicControls.create(CapacitorMusicControls.java:42)

How to pause on android?

How can I pause the player controls? It says that updateElapsed() and updatePlaying() are not implemented on android. Also the controls are not destroyed if the user ends the app.

Fatal error: Unexpectedly found nil while unwrapping an Optional value

Running the app on an iPhone 5s simulator with iOS 12.4 produces the following runtime error in Xcode:

Fatal error: Unexpectedly found nil while unwrapping an Optional value: file CapacitorMusicControlsPluginNew/Plugin.swift, line 175
2022-07-11 13:29:20.835727+0200 App[75764:805906] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file CapacitorMusicControlsPluginNew/Plugin.swift, line 175

concerning the following Code:

if(urlPath != nil && defaultManager.fileExists(atPath: urlPath!)){
    coverImage = UIImage(contentsOfFile: urlPath!)! // <- issue is this null-safety operator on UIImage()
} else {
    coverImage = nil;
}

I guess iPhones of older architecture are handling null safety differently or not at all. Is there a way to handle this without the app crashing?

error: cannot find symbol PendingIntent.FLAG_MUTABLE

Hello I am getting following error:

..../app/node_modules/capacitor-music-controls-plugin-new/android/src/main/java/com/gokadzev/capacitormusiccontrols/MusicControlsNotification.java:256: error: cannot find symbol
resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, PendingIntent.FLAG_MUTABLE);
^
symbol: variable FLAG_MUTABLE
location: class android.app.PendingIntent

Do you know what is causing the issue and how to fix that?

Screenshot 2022-06-17 at 12 06 20
Screenshot 2022-06-17 at 12 05 52

Controls not showing

Hello, thank you for this plugin. Sadly, the controls aren't showing on my Android (8.1.0) Device. This is how I use the plugin:

import { CapacitorMusicControls } from 'capacitor-music-controls-plugin-new';
...
CapacitorMusicControls.create({
        track: 'Lorem Ipsum',
        ticker: 'Lorem Ipsum',
        artist: 'Lorem Ipsum',
        album: 'Lorem Ipsum',
        cover: 'https://dummyimage.com/300/09f/fff.png',
        hasPrev: false,
        hasNext: false,
        hasSkipForward: true,
        hasSkipBackward: true,
        skipForwardInterval : 15,
        skipBackwardInterval : 15,
        hasScrubbing: true,
        isPlaying   : true,
        dismissable : false,
      }).then(() => {
        console.log('Media Session initialized');
      }).catch(e => {
        console.log(e);
      });

AndroidManifest.xml

<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

MainActivity.java

import android.os.Bundle;
import com.getcapacitor.BridgeActivity;
import com.gokadzev.capacitormusiccontrols.CapacitorMusicControls;

public class MainActivity extends BridgeActivity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Additional plugins you've installed go here
    registerPlugin(CapacitorMusicControls.class);
  }
}

Podspec error upon sync

Just an FYI, currently getting:

[error] Analyzing dependencies
        [!] No podspec found for `CapacitorMusicControlsPluginNew` in
        `../../node_modules/.pnpm/github.com+gokadzev+capacitor-music-controls-plugin-new@2c3937e8e77cb50775269b6ddfa153c9a41b9b96/node_modules/capacitor-music-controls-plugin-new`

When running cap sync.

PendingIntent: Targeting S+ (version 31 and above) requires FLAG_IMMUTABLE or FLAG_MUTABLE

I'm using Angular 12 with Capacitor and this Plugin, set the compileSdkVersion and targetSdkVersion to 31 in variables.gradle (I prefer not to put them to 31 as this can cause a lot of issues down the line). When I start the app on Android I get this error:

 Caused by: java.lang.IllegalArgumentException: ch.pomona.newsapp: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
    Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
        at android.app.PendingIntent.checkFlags(PendingIntent.java:375)
        at android.app.PendingIntent.getBroadcastAsUser(PendingIntent.java:645)
        at android.app.PendingIntent.getBroadcast(PendingIntent.java:632)
        at com.gokadzev.capacitormusiccontrols.MusicControlsNotification.createBuilder(MusicControlsNotification.java:209)
        at com.gokadzev.capacitormusiccontrols.MusicControlsNotification.updateNotification(MusicControlsNotification.java:81)
        at com.gokadzev.capacitormusiccontrols.CapacitorMusicControls.updateMetadata(CapacitorMusicControls.java:224)
        at com.gokadzev.capacitormusiccontrols.CapacitorMusicControls.create(CapacitorMusicControls.java:42)
        	... 9 more

I solved it by reverting back to API level 30 instead of 31 and forcing the androidx.appcompat dependency to version 1.2.0 (instead of 1.4.2 that will be picked otherwise):

in your app/build.gradle:

dependencies {
    implementation("androidx.appcompat:appcompat:$androidxAppCompatVersion") {
        force = true
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.