Giter Site home page Giter Site logo

ghenry22 / cordova-plugin-music-controls2 Goto Github PK

View Code? Open in Web Editor NEW

This project forked from homerours/cordova-music-controls-plugin

58.0 6.0 58.0 988 KB

A Cordova plugin displaying music controls in notifications (cordova-plugin-music-controls)

License: MIT License

Java 56.76% Objective-C 33.14% JavaScript 10.11%

cordova-plugin-music-controls2's Introduction

Cordova Music Controls Plugin 2

Music controls for Cordova 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).

This plugin is forked from the original which is no longer maintained but which can be found at: https://github.com/homerours/cordova-music-controls-plugin

This plugin is renamed as cordova-plugin-music-controls2 for easy differentiation and to allow for publishing updates to npm to make life easier for everyone.

Supported platforms

Installation

  • Current release cordova plugin add cordova-plugin-music-controls2
  • Bleeding edge direct from github cordova plugin add https://github.com/ghenry22/cordova-plugin-music-controls2

Methods

  • Create the media controls:
MusicControls.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://...')
	isPlaying   : true,							// optional, default : true
	dismissable : true,							// optional, default : false

	// 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

	// iOS only, optional
	
	duration : 60, // optional, default: 0
	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: 0.
	skipBackwardInterval : 15, //optional. default: 0.
	hasScrubbing : false, //optional. default to false. Enable scrubbing from control center progress bar 

	// Android only, optional
	// 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'
}, onSuccess, onError);
  • Destroy the media controller:
MusicControls.destroy();
  • Subscribe events to the media controller:
function events(action) {

  const message = JSON.parse(action).message;
	switch(message) {
		case 'music-controls-next':
			// Do something
			break;
		case 'music-controls-previous':
			// Do something
			break;
		case 'music-controls-pause':
			// Do something
			break;
		case 'music-controls-play':
			// Do something
			break;
		case 'music-controls-destroy':
			// Do something
			break;
    	case 'music-controls-toggle-play-pause' :
			// Do something
			break;
		// Lockscreen seek controls (iOS only)
    	case 'music-controls-seek-to':
			const seekToInSeconds = JSON.parse(action).position;
			MusicControls.updateElapsed({
				elapsed: seekToInSeconds,
				isPlaying: true
			});
			// 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;
	}
}

// Register callback
MusicControls.subscribe(events);

// Start listening for events
// The plugin will run the events function each time an event is fired
MusicControls.listen();
  • Toggle play/pause:
MusicControls.updateIsPlaying(true); // toggle the play/pause notification button
MusicControls.updateDismissable(true);
  • iOS Specific Events: Allows you to listen for iOS events fired from the scrubber in control center.
MusicControls.updateElapsed({
	elapsed: 208, // seconds
	isPlaying: true
});

List of media button events

  • Default:
'music-controls-media-button'
  • Android only:
'music-controls-media-button-next', 'music-controls-media-button-pause', 'music-controls-media-button-play',
'music-controls-media-button-play-pause', 'music-controls-media-button-previous', 'music-controls-media-button-stop',
'music-controls-media-button-fast-forward', 'music-controls-media-button-rewind', 'music-controls-media-button-skip-backward',
'music-controls-media-button-skip-forward', 'music-controls-media-button-step-backward', 'music-controls-media-button-step-forward',
'music-controls-media-button-meta-left', 'music-controls-media-button-meta-right', 'music-controls-media-button-music',
'music-controls-media-button-volume-up', 'music-controls-media-button-volume-down', 'music-controls-media-button-volume-mute',
'music-controls-media-button-headset-hook'
  • iOS Only:
'music-controls-skip-forward', 'music-controls-skip-backward'

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

cordova-plugin-music-controls2's People

Contributors

0505gonzalez avatar alexious-sh avatar alisonmonteiro avatar cveniamin avatar danpastori avatar darthdie avatar decates avatar eltonfaust avatar filiphsps avatar ghenry22 avatar hdezela avatar homerours avatar jh3141 avatar neoassyrian avatar therockettek avatar titannano avatar vmartins avatar yoojene avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

cordova-plugin-music-controls2's Issues

Requires BLUETOOTH and BLUETOOTH_ADMIN permissions on Android

I'm using version 3.0.3, and just switched from the old repo to fix an issue with iOS (thank you!).

However, it looks like plugin.xml for this plugin is now requesting additional permissions on Android, including android.permission.BLUETOOTH and android.permission.BLUETOOTH_ADMIN.

The commit in which this change was made simply has the comment 'update package name ready for publish', so I wonder if this is an accidental change that shouldn't be included? If not, what's the reason for requesting these additional permissions on Android? Thanks.

Lockscreen: disabling previous / next controls

First of all thanks for a very nice plugin @ghenry22

Question: is there a way to disable the previous / next controls on the lock screen?
In my case I'm playing one long piece of media -- and there is no previous or next media.

I tried using
hasPrev: false,
hasNext: false
But these will disable the controls in the notifications area (not on the lock screen).

Thanks

Android & iOS necessary settings

@ghenry22

Great job!
That will be nice if you will add to the installation section suggestions for necessary settings for src-cordova/config.xml file

For Android - inside <platform name="android">:

<config-file target="AndroidManifest.xml" parent="/*">
  <uses-permission android:name="android.permission.WAKE_LOCK" />
</config-file>

For iOS - inside <platform name="ios">:

<config-file target="*-Info.plist" parent="UIBackgroundModes">
  <array>
    <string>audio</string>
  </array>
</config-file>

Failed to fetch plugin

Hello,
today we tried to install the plugin again. But i fails on windows and on os x.

We used the ionic syntax and the tried the cordova syntax:

ionic cordova plugin add https://github.com/ghenry22/cordova-music-controls-plugin.git
cordova plugin add https://github.com/ghenry22/cordova-music-controls-plugin

With the ancestor version from homerours the installation works.

Regards
nowrap

iOs: Music Controls always start with the pause icon, regardless of 'isPlaying' setting.

this.musicCtrl.create({
      track: track_title,
      artist: this.book.author,
      cover: this.book.thumbURL,
      isPlaying: false,
      dismissable: true
     }) 

Irrespective of whether or not I call:
this.musicCtrl.updateElapsed({ isPlaying: false, elapsed: this.trackPosition }); or
this.musicCtrl.updateIsPlaying(false);

The music control always shows the lock screen controls with the paused icon at the beginning. It only seems to honor a touch event to change the icon.

Any ideas?

Does not work properly on iOS

I have tried some solutions to make it work on iOS, but none of them seem to work.

The weird part is that it did work a few times after I left the audio playing in my application. Now I am unable to make it work.

Does anyone have any idea about how to solve this?

Service should be running in foreground mode

We are facing the issue that Android (at least 10+) is killing our network connection and thereby also our audio stream after about ~5 minutes.
The problem appears to be, that the service created by this plugin is not running in foreground mode. Calling startForeground in the service, is currently fixing our issue. I will create a pull request that should fix this problem.

Pause icon won't change

I've not installed the background mode, and I'm using native media plugin as you recommended.

I'm waiting for the event running to create controls, but then if I pause the music, the notification icon wont change.

    this.music = this.media.create(trackSrc)
      this.music.onStatusUpdate.subscribe(
        (status) => {
          switch (status) {
              case this.media.MEDIA_STARTING:
              break;
              case this.media.MEDIA_RUNNING:
                this.loadMusicControls() // LOAD MUSIC CONTROLS
              break;
          }}
       )
      this.music.play()

And this is how I create the controls:

loadMusicControls()
  {
    MusicControls.destroy()

    // Music Controls
    MusicControls.create({
      track       : this.currentlyPlaying().title,	
      artist      : this.currentlyPlaying().author,					
      cover       : this.bookCover,	
    
      // hide previous/next/close buttons:
      hasPrev   : false,		// show previous button, optional, default: true
      hasNext   : false,		// show next button, optional, default: true
      hasPause   : true,		// show pause button, optional, default: false
      hasClose  : true,		// show close button, optional, default: false
    }, (s) =>{},  (error) =>{});
    
    function eventsReader(playListService, action) {
       ...
    }

    MusicControls.subscribe((events) => {eventsReader(this, events)});

    // Start listening for events
    // The plugin will run the events function each time an event is fired
    MusicControls.listen();

  }

iOS: music controls with TTS?

Hi,

Excellent plugin, thank you. I'm using it for an Android text-to-speech TTS project (read text from a page - and the user can play/stop the reading using the MusicControls) and it works perfectly.

On iOS it does not seem to load the music controls when the text to speech reading is active (audio can be heard). Here is some sample code to illustrate how I'm using it. My iOS device is an iPhone SE with iOS 13.4.1 (in case that's helpful). I have also tried with iPhone 8 XCode simulator running iOS 14.4.
** EDIT: the controls are launched on the simulator for iPhone 8 with iOS 14.4 (but not on the device with iOS 13.4.1), once i removed the following lines from the config.xml file. Oddly enough it does not fire the following functions: onMusicControlsCreateSuccess() or onMusicControlsCreateFailure() on either platform**

        <config-file target="*-Info.plist" parent="UIBackgroundModes">
          <array>
            <string>audio</string>
          </array>
        </config-file>

Using the code below, neither the onMusicControlsCreateSuccess() nor the onMusicControlsCreateFailure() seem to fire.

I'm not sure if the issue is with TTS + Music Controls use or if I'm doing something wrong.
Note: have also installed your plugin from https://github.com/ghenry22/cordova-plugin-background-mode on iOS

  • and enabled Xcode's background mode for audio

Any advice is welcome. Thanks.

...
// User has clicked a button on the app to read the screen content
//    reading begins successfully and can be heard on iOS  & android. 
// Next we want to fire up the controls to let the user stop the playing from the home screen / notification area
//    this works on Android but not for iOS

let musicControlOptions = {
	track: voiceTrack,
	artist: voiceArtist,
	album: voiceAlbum,
	dismissable : true,
	hasPrev: true,
	hasNext: true,
	hasClose: true,
	isPlaying: false
};
if (vDevice === 'ios' || vDevice === 'android') { // the vDevice variables are set earlier             
      if (vDevice === 'ios'){
           let isBGModeActive = cordova.plugins.backgroundMode.isActive();
           if (isBGModeActive === false) {
                 cordova.plugins.backgroundMode.enable();
             }
             console.log('bgmode: ', isBGModeActive); // this is logged properly, gives true if in background
       }
                 
        MusicControls.create(musicControlOptions, onMusicControlsCreateSuccess, onMusicControlsCreateFailure);

// other code here  
}

function onMusicControlsCreateFailure() {
        console.log('could not create controls'); // this is not logged, appears not to fire for iOS
}
function onMusicControlsCreateSuccess() {
        MusicControls.updateIsPlaying(true);
        console.log('success creating controls'); // this is not logged, appears not to fire for iOS
  // more code to handle player button events

        MusicControls.subscribe(events);
        MusicControls.listen();
}

```

FOREGROUND SERVICE in Android

I have a question with the logic of this library because i don't understand, why you don't use FOREGROUND SERVICE in Android?

it's supposed to be necessary to have something playing in background

thanks

Android: random crashes

Android 10

I get my app crashed from time to time with errors:

10-26 06:33:30.516 11500 23961 E AndroidRuntime: FATAL EXCEPTION: pool-1-thread-24
10-26 06:33:30.516 11500 23961 E AndroidRuntime: Process: com.museria.musiphone, PID: 11500
10-26 06:33:30.516 11500 23961 E AndroidRuntime: java.lang.IllegalArgumentException: Duplicate key in ArrayMap: null
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at android.os.Parcel.createException(Parcel.java:2078)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at android.os.Parcel.readException(Parcel.java:2042)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at android.os.Parcel.readException(Parcel.java:1990)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at android.app.INotificationManager$Stub$Proxy.enqueueNotificationWithTag(INotificationManager.java:2776)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at android.app.NotificationManager.notifyAsUser(NotificationManager.java:497)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at android.app.NotificationManager.notify(NotificationManager.java:447)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at android.app.NotificationManager.notify(NotificationManager.java:423)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at com.homerours.musiccontrols.MusicControlsNotification.updateNotification(MusicControlsNotification.java:75)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at com.homerours.musiccontrols.MusicControls$2.run(MusicControls.java:149)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at java.lang.Thread.run(Thread.java:919)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: Caused by: android.os.RemoteException: Remote stack trace:
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at android.util.ArrayMap.validate(ArrayMap.java:672)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at android.os.Parcel.readArrayMapInternal(Parcel.java:3259)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at android.os.BaseBundle.initializeFromParcelLocked(BaseBundle.java:292)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at android.os.BaseBundle.unparcel(BaseBundle.java:236)
10-26 06:33:30.516 11500 23961 E AndroidRuntime: 	at android.os.Bundle.getParcelable(Bundle.java:951)

or

10-24 17:48:11.555 27921 28882 E AndroidRuntime: FATAL EXCEPTION: pool-1-thread-8
10-24 17:48:11.555 27921 28882 E AndroidRuntime: Process: com.museria.musiphone, PID: 27921
10-24 17:48:11.555 27921 28882 E AndroidRuntime: java.util.ConcurrentModificationException
10-24 17:48:11.555 27921 28882 E AndroidRuntime: 	at android.util.ArrayMap.put(ArrayMap.java:583)
10-24 17:48:11.555 27921 28882 E AndroidRuntime: 	at android.os.Bundle.putParcelable(Bundle.java:507)
10-24 17:48:11.555 27921 28882 E AndroidRuntime: 	at android.app.Notification.addFieldsFromContext(Notification.java:2987)
10-24 17:48:11.555 27921 28882 E AndroidRuntime: 	at android.app.Notification.addFieldsFromContext(Notification.java:2980)
10-24 17:48:11.555 27921 28882 E AndroidRuntime: 	at android.app.Notification$Builder.build(Notification.java:5894)
10-24 17:48:11.555 27921 28882 E AndroidRuntime: 	at com.homerours.musiccontrols.MusicControlsNotification.updateNotification(MusicControlsNotification.java:74)
10-24 17:48:11.555 27921 28882 E AndroidRuntime: 	at com.homerours.musiccontrols.MusicControls$2.run(MusicControls.java:149)
10-24 17:48:11.555 27921 28882 E AndroidRuntime: 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
10-24 17:48:11.555 27921 28882 E AndroidRuntime: 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
10-24 17:48:11.555 27921 28882 E AndroidRuntime: 	at java.lang.Thread.run(Thread.java:919)

or

10-24 14:10:12.936 20170 14568 E AndroidRuntime: FATAL EXCEPTION: pool-1-thread-48
10-24 14:10:12.936 20170 14568 E AndroidRuntime: Process: com.museria.musiphone, PID: 20170
10-24 14:10:12.936 20170 14568 E AndroidRuntime: java.lang.IllegalStateException: finishBroadcast() called outside of a broadcast
10-24 14:10:12.936 20170 14568 E AndroidRuntime: 	at android.os.RemoteCallbackList.finishBroadcast(RemoteCallbackList.java:320)
10-24 14:10:12.936 20170 14568 E AndroidRuntime: 	at android.support.v4.media.session.MediaSessionCompat$MediaSessionImplApi21.setPlaybackState(MediaSessionCompat.java:3464)
10-24 14:10:12.936 20170 14568 E AndroidRuntime: 	at android.support.v4.media.session.MediaSessionCompat.setPlaybackState(MediaSessionCompat.java:715)
10-24 14:10:12.936 20170 14568 E AndroidRuntime: 	at com.homerours.musiccontrols.MusicControls.setMediaPlaybackState(MusicControls.java:237)
10-24 14:10:12.936 20170 14568 E AndroidRuntime: 	at com.homerours.musiccontrols.MusicControls.access$300(MusicControls.java:42)
10-24 14:10:12.936 20170 14568 E AndroidRuntime: 	at com.homerours.musiccontrols.MusicControls$2.run(MusicControls.java:168)
10-24 14:10:12.936 20170 14568 E AndroidRuntime: 	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
10-24 14:10:12.936 20170 14568 E AndroidRuntime: 	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
10-24 14:10:12.936 20170 14568 E AndroidRuntime: 	at java.lang.Thread.run(Thread.java:919)

What can be the reason?

Fuzzy icons

Hi there. All the notification icons on my android device (play, pause, next, previous) are blurred somewhat, have tested on a variety of tablets and handsets. On the lock screen however, they are fine. Has anyone else experienced this?

I can't import

Hi,
I tried to use this plugin but when i try to import the module i had error, the error is like it,
'Cannot find module 'cordova-plugin-music-controls2' or its corresponding type declarations'
i don't know if im doing someting wrong but if anyone can helpme, thanks

Control media from external bluetooth device

When implementing this on Android I seem to be unable to view or control the media playback using external bluetooth devices - (like my Mi Band 4). - (It doesn't pick up that music is playing). Does this feature work for others or any suggestions on how to get it to work?
Thanks

Lockscreen cover image doesn't go away

On Android (8) when using this plugin with the cover parameter set to an image all seems to be working fine.

I get the cover image in the notification.
I also get the cover image on the lockscreen (when the phone is locked and I power on the screen).

Problem is when I destroy the notification. The cover image on the lockscreen does not go away.
I have to close my app for the original lockscreen image (what the user had as his default) to come back.

tldr: cover image on lockscreen is persistent even after notification destroy.

implmenetation error

Error: package android.support.v4.media.session does not exist.

Are you gonna implement them?

Temporary fix:

Short Version:

Add the following line to your build.gradle file:
implementation 'com.android.support:support-v4:YOUR_TARGET_VERSION' 

Long Version:

Go to File -> Project Structure

Go to "Dependencies" Tab -> Click on the Plus sign -> Go to "Library dependency"

Select the support library "support-v4 (com.android.support:support-v4:YOUR_TARGET_VERSION)"

Navigate to your "build.gradle" inside your App Directory and double check if your desired Android Support Library has been added to your dependencies.

Rebuild your project and now everything should work.

Progress bar not showing in android

I've got the notification successfully but I'm not getting a progress bar inside notification. I'm using android device. Here's my code:

  createMusicControls() {
    this.musicControls.create({
      track: 'Time is Running Out',
      artist: 'Muse',
      cover: `${this.file.externalDataDirectory}1617201823790.png`,
      isPlaying: true,
      dismissable: false,

      hasPrev: true,      
      hasNext: true,      
      hasClose: true,       

      album: 'Absolution',     
      duration: 60, 
      elapsed: 10, 
      hasSkipForward: true,  
      hasSkipBackward: true,
      skipForwardInterval: 15,
      skipBackwardInterval: 15, 
      hasScrubbing: true, 

      ticker: 'Now playing "Time is Running Out"',
      playIcon: 'media_play',
      pauseIcon: 'media_pause',
      prevIcon: 'media_prev',
      nextIcon: 'media_next',
      closeIcon: 'media_close',
      notificationIcon: 'notification'
    });
  }

Issue with Android build

platforms\android\app\src\main\java\com\homerours\musiccontrols\MusicControls.java:235: error: cannot find symbol

playbackstateBuilder.setState(state, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 0);
^(this should be under "PlaybackStateCompat.") but formatting won't work
symbol: variable PlaybackStateCompat
location: class MusicControls

dependencies
"cordova-android": "8.1.0",
"cordova-plugin-music-controls2": "git+https://github.com/ghenry22/cordova-plugin-music-controls2.git", (also tried version 3.0.3
ionic: 5.20.0

It does not intercept changes from other media applications

Android 10, MIUI 11, mi9t

Let's say there is a song is playing with the library controls. If i run some youtube video or any other media, then nothing is happening in the control buttons. But the play button should appear instead of the pause one, to be able to switch back to my song.

html5 Music Source

hello,
i've been trying to make this plugin work on my app that play music from an html web source & not from the device,
when the html source is loaded to chrome on android it shows the music playing on the device lock screen,
when the same html link is opened & played from the android app nothing shows on the locked screen,
i read that The Media Session API is supported in Chrome only, so is there a way to make it work in cordova android ?
by the way it works with no issue on the IOS side,
regards

Multiple instanses

Android 10.

The case:

I build 2 apps with the library. I run one song in the first app and then another one in the second. So there are two notifications with the controls. When i click on any button(at least prev/next) both apps get the event message.

I see two solutions:

  1. Perfectly, if the library can distinguish the apps some way and send the message only for the necessary one.
  2. If it is too problematic, the library can at least send the application name with the event to let the programmer distinguish it in the code. const application= JSON.parse(action).application;

build errors possibly related to pull requests

Hello, I'm getting quite a few build errors and most of them seem to be related to this pull requests:
MediaSessionCompat error on API 20 or earlier
Added support framework
I've added the plugin cordova-plugin-android-support-v4 and reduced many errors, but still getting this:

MediaSessionCallback.java:54: error: method does not override or implement a method from a supertype
MediaSessionCallback.java:56: error: cannot find symbol
    super.onPlayFromMediaId(mediaId, extras);
         ^
  symbol: method onPlayFromMediaId(String,Bundle)
MusicControls.java:72:` error: cannot find symbol
		this.mediaSessionCompat.setMediaButtonReceiver(this.mediaButtonPendingIntent);
		                       ^
  symbol:   method setMediaButtonReceiver(PendingIntent)
  location: variable mediaSessionCompat of type MediaSessionCompat
MusicControls.java:80: error: cannot find symbol
		this.mediaSessionCompat.setMediaButtonReceiver(null);
		                       ^
  symbol:   method setMediaButtonReceiver(<null>)
  location: variable mediaSessionCompat of type MediaSessionCompat

MusicControls.java:103: error: no suitable constructor found for MediaSessionCompat(Context,String,<null>,PendingIntent)
		this.mediaSessionCompat = new MediaSessionCompat(context, "cordova-music-controls-media-session", null, this.mediaButtonPendingIntent);
		                          ^
    constructor MediaSessionCompat.MediaSessionCompat(Context,String) is not applicable
      (actual and formal argument lists differ in length)
    constructor MediaSessionCompat.MediaSessionCompat(MediaSessionImpl) is not applicable
      (actual and formal argument lists differ in length)

Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: ...platforms/android/app/src/main/java/org/apache/cordova/file/AssetFilesystem.java uses unchecked or unsafe operations.

Is there any chances to get some hints on this??
some environment info:

[email protected] with:
[email protected]
[email protected]
[email protected]
[email protected]

Environment:
OS: linux
Node: v12.11.1
npm: 6.11.3

Plugins:
cordova-music-controls
cordova-plugin-android-support-v4
cordova-plugin-file
cordova-plugin-inappbrowser
cordova-plugin-media
cordova-plugin-multi-player
cordova-plugin-whitelist

Available Android targets: 100% Fetch remote repository.
id: 1 or "android-28"
Name: Android API 28
Type: Platform
API level: 28
Revision: 6

cordova requirements android
Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: installed android-28
Gradle: installed /usr/share/java/gradle/bin/gradle

thanks in advance

Android: Notification destroyed when application move to background

Hi

I am using this plugin in ionic 2 application. I am calling create method once my audio is loaded completely. I am able to create the music controls notification with the necessary data when application is in front end, but when application moves to back ground, notification automatically disappears. Also, I have observed that when the second song loads in background the updated notification appears itself.

This is my sample code snippet:

let musicControllOptions = {
        track: this.trackToPlay.title,
        artist: this.trackToPlay.artist,
        cover: this.trackToPlay.art,      // optional, default : nothing
        isPlaying: false,                         // optional, default : true
        dismissable: false,                         // optional, default : false
        // hide previous/next/close buttons:
        hasPrev: true,      // show previous button, optional, default: true
        hasNext: true,      // show next button, optional, default: true
        hasClose: true,       // show close button, optional, default: false
        // iOS only, optional
        album: this.trackToPlay.title,     // optional, default: ''
        duration: this.duration, // optional, default: 0
        elapsed: this.saturation, // optional, default: 0
        // Android only, optional
        ticker: 'Now playing ' + this.trackToPlay.title
    };
    this.musicControls.destroy();
    this.musicControls.create(musicControllOptions)

Is there any other option I have to use for showing notification in background mode?

Environment info:
cli packages:

@ionic/cli-utils  : 1.12.0
ionic (Ionic CLI) : 3.12.0

global packages:

cordova (Cordova CLI) : 8.1.2 ([email protected]) 

local packages:

@ionic/app-scripts : 1.1.4
Cordova Platforms  : android 8.1.0 browser 5.0.4 ios 4.5.5
Ionic Framework    : ionic-angular 2.3.0

System:

Android SDK Tools : 26.1.1
Node              : v10.16.3
npm               : 6.9.0 
OS                : Linux 4.15

Misc:

backend : pro

Clicking pause in Android shade doesn't change icon

After triggering MusicControls.create(), everything gets created properly in the Android shade and you can see the pause button. When you click the pause button, the music-controls-pause event is triggered but the icon doesn't change to a play button. If I force the change using the following code, the iOS duration slider resets:

MusicControls.updateIsPlaying(false); 
MusicControls.updateDismissable(true);

Shouldn't Android automatically change from a pause button to a play button just like iOS?

Tested on Android 7 and 10 with the same results.

Android platform 8.1.0
Cordova 9.0.0

Android - Events not firing from lock screen

On Android 9 - Samsung Galaxy A70. Events (play/pause/next/previous) are not being recorded from the lock screen. Works fine from the notification tray.

On emulators, it works fine and as expected.

Background Color

Could you add an option to custom the background from the notification? Something like the react native plugin

Clarifications & requests

First off, thank your for creating this. It works fantastically on iOS 14.1 (currently latest version).

A couple of questions.

  1. Can you explain what 'MusicControls.updateDismissable' does?
  2. I would like to put an 'Airplay' button on my UIView that launches the Airplay selection modal. Is this available in your plugin? If not, do you have an idea on how that could be achieved.

Thanks again GH.

Android - Stuck notification

Hi,

Some of my users reported that sometimes the notification cannot be removed from the notification center while nothing is playing. The only way to remove it is by killing the app. I've also experienced this on a Pixel 4 with Android 10.
I've updated the app to display the close button on the notification but it has no effect when this happens, otherwise the button works.

I don't have much information.

Do you have any idea what could do this?

Thanks

Bug with play button

Hello,

I am using your plugin for my application, at the moment I am having two problems.

The first is that I can't change the state of the play button, it is always displayed in play.

The second is when I decided to close my iOs to test the player from the lockscreen, my player disappears to display a pleasure with only "Ionic App" for information.

Thanks for your help !

Install url

Hello, I've noticed the install url given in the Readme is the one pointing to the Homerours github:

Installation
cordova plugin add https://github.com/homerours/cordova-music-controls-plugin)

Is this correct? I mean, does this url forwards to this fork? or should I just use your github url like this:
cordova plugin add https://github.com/ghenry22/cordova-music-controls-plugin

I've tried both and got this two different results:

  • original github:
cordova plugin add https://github.com/homerours/cordova-music-controls-plugin
cordova plugin ls
cordova-plugin-music-controls 2.2.0 "MusicControls"
  • forked github:
cordova plugin add https://github.com/ghenry22/cordova-music-controls-plugin
cordova plugin ls                                                           
cordova-music-controls 2.2.1 "MusicControls"

Which one should I use?
Thanks!

Use base64 string for image

Storing an image in device storage and again retrieving from it to show in notification seems time consuming and bulky. It would be better if we are directly able to use base64 string to show image inside notification which I'm trying to achieve with below code but unable to do it

sampleCover = '---base64 string---';
this.musicControls.create({
      cover: this.sampleCover,      
      ...

No image is coming in notification through this code. Is there any workaround to show the image through base64 string?

Ionic android build not working out of the box

Steps

git clone https://github.com/ionic-team/ionic-conference-app.git
cd ionic-conference-app
npm install
npm install cordova-plugin-music-controls2 --save
ionic cordova plugin add cordova-plugin-music-controls2

in src/app/app.module.ts import:

import * as MusicControls from 'cordova-plugin-music-controls2/www/MusicControls';

followed by

ionic cordova build android

Results in:

Task :app:compileDebugJavaWithJavac FAILED
/home/me/git/ionic-conference-app/platforms/android/app/src/main/java/com/homerours/musiccontrols/MediaSessionCallback.java:5: error: package android.support.v4.media.session does not exist
import android.support.v4.media.session.MediaSessionCompat;

I am not very experienced with ionic/cordova so I might be doing something wrong. I also noticed there is no angular module exports available so I have to import the library as a native js which is not ideal. That would be a nice addition to the project.

A minimum documentation how to properly include and use the project in an ionic app would also be helpful.

Does not work on iOS

I have problems trying to implement this plugin on IOS, all attempts I made were unsuccessful, on android works!

I tried to start this plugin without media, with video, with audio, both situations realize that it is the webview that creates the controls and not the plugin, the next and back controls are always disabled! I can't manipulate these controls created by webview? Or is there a way to replace these controls with this plugin?
Image of Yaktocat

iOS Lock Screen Controls Only Show Intermittently

I am using cordova-plugin-media and this plugin to play music and provide controls for users on the home screen for iOS. The below implementation is not entirely finished, but is at a point where it should work. My issue is that the controls only sometimes appear, other times nothing shows at all, and sometimes the controls show, but then disappear after a few minutes. Can anyone provide insight into how I can get the controls to always show, instead of randomly working some of the time after an app restart? It is the exact same code every times.

I have the background audio capability turned on inside my xcode project too.

`import AudioPlayerStore, { IAudioPlayerMetadata } from "../../../main/sharedStores/AudioPlayerStore";
import { IAudioPlayer } from "../interfaces/IAudioPlayer";

/** How often the duration is updated */
const TIMER_UPDATE: number = 1000;

declare var MusicControls: any;

/** The amount of time to skip forward and back */
const SKIP_DURATION_IN_SECONDS: number = 15;

export class CordovaAudioPlayer implements IAudioPlayer
{
// Varaibles
// =======================================

/** The instance of the cordova audio player */
private audioPlayer!: Media;

/** The reference to the timeout */
private updateTime: number = 0;

/** Whether or not the current audio is loading */
public isLoading: boolean = false;

/** The current time (in seconds) of the audio */
public currentTime: number = 0;

/** The total duration (in seconds) of the audio */
public duration: number = 0;

// Setup
// =======================================

constructor(public metaData: IAudioPlayerMetadata)
{
    this.audioPlayer = new Media(
        this.metaData.source,
        this.onPlayEnded.bind(this),
        this.onError.bind(this),
        this.statusChange.bind(this)
    );

    this.isLoading = true;
    this.play();
}

// Implements
// =======================================

/**
 * Play the audio
 */
public play(): void { this.audioPlayer.play(); }

/**
 * Pause the audio
 */
public pause(): void { this.audioPlayer.pause(); }

/**
 * Reset the player
 */
public reset(): void
{
    this.audioPlayer.stop();
    this.audioPlayer.release();
}

/**
 * Update the players current time
 *
 * @param time the new current time to set
 */
public setCurrentTime(time: number): void
{
    this.audioPlayer.seekTo(time * 1000);
    this.currentTime = time;

    MusicControls.updateElapsed({ elapsed: time });
}

private async statusChange(code: number): Promise<void>
{
    switch (code)
    {
        case Media.MEDIA_NONE:
            console.log("No media")
            break

        case Media.MEDIA_STARTING:
            console.log("Media starting");
            break

        case Media.MEDIA_RUNNING:
            console.log("Media running");

            this.duration = this.audioPlayer.getDuration();
            this.updateTime = setInterval(this.updateCurrentTime.bind(this), TIMER_UPDATE);
            this.updateCurrentTime();

            MusicControls.create({
                track: this.metaData.title,
                artist: this.metaData.author,
                hasSkipForward: true,
                hasSkipBackward: true,
                skipForwardInterval: 15,
                skipBackwardInterval: 15,
                duration: this.duration,
                elapsed: this.currentTime,
            }, () =>
            {
                console.log("Success but never gets called")
            }, this.onError.bind(this));

            MusicControls.subscribe(this.events.bind(this));
            MusicControls.listen();
            MusicControls.updateIsPlaying(true);

            AudioPlayerStore.instance.setIsPlaying(true);
            this.isLoading = false;

            break;

        case Media.MEDIA_PAUSED:
            clearInterval(this.updateTime);
            MusicControls.updateIsPlaying(false);
            AudioPlayerStore.instance.setIsPlaying(false);
            break;

        case Media.MEDIA_STOPPED:
            clearInterval(this.updateTime);
            this.isLoading = false;
            this.currentTime = 0;
            this.duration = 0;
            MusicControls.destroy();
            break;

        default:
            break;
    }
}

// Helpers
// =======================================

/**
 * Get the current players position wrapped in a promise
 */
private async getPlayerPosition(): Promise<number>
{
    return new Promise<number>((resolve, reject) =>
    {
        this.audioPlayer
            .getCurrentPosition((currentTime: number) => resolve(currentTime), (error: any) => reject(error))
    });
}

private onPlayEnded(): void { AudioPlayerStore.instance.setIsPlaying(false); }

private events(action: string): void
{
    const message = JSON.parse(action).message;
    switch (message)
    {
        case 'music-controls-skip-forward':
            const newForwardTime: number = Math.min(this.currentTime + SKIP_DURATION_IN_SECONDS, this.duration);
            this.setCurrentTime(newForwardTime);
            break;
        case 'music-controls-skip-backward':
            const newBackwardTime: number = Math.max(this.currentTime - SKIP_DURATION_IN_SECONDS, 0);
            this.setCurrentTime(newBackwardTime);
            break;
        case 'music-controls-pause':
            this.audioPlayer.pause(); 
            break;
        case 'music-controls-play':
            this.audioPlayer.play();
            break;
        case 'music-controls-destroy':
            // Do something
            break;

        // External controls (iOS only)
        case 'music-controls-toggle-play-pause':
            // Do something
            break;
        case 'music-controls-seek-to':
            const seekToInSeconds = JSON.parse(action).position;
            this.setCurrentTime(seekToInSeconds);
            break;

        default:
            break;
    }
}

private onError(err: any)
{
    console.log(err);
}

private async updateCurrentTime(): Promise<void>
{
    const elapsed: number = await this.getPlayerPosition();
    this.currentTime = elapsed;
    MusicControls.updateElapsed({ elapsed });
}

}
`

Play button always displayed

Hello,

I am using your plugin for my application, at the moment I am having two problems.

The first is that I can't change the state of the play button, it is always displayed in play.

The second is when I decided to close my iOs to test the player from the lockscreen, my player disappears to display a pleasure with only "Ionic App" for information.

Thanks for your help !

Background color extracted from the album artwork (based on react plugin)

Hi! Acording to this in the react version of this plugin (color, and colorized) could be posible to integrate here:

MusicControl.setNowPlaying({
  title: 'Billie Jean',
  artwork: 'https://i.imgur.com/e1cpwdo.png', 
  ...
  color: 0xFFFFFF, // Android Only - Notification Color
  colorized: true, // Android 8+ Only - Notification Color extracted from the artwork. Set to false to use the color property instead
  ...
})

This are the lines where colorized is set.
https://github.com/tanguyantoine/react-native-music-control/blob/master/android/src/main/java/com/tanguyantoine/react/MusicControlModule.java#L402

Music control module imports:
import androidx.core.app.NotificationCompat;
which after using its Builder they set the colorize property

nb = new NotificationCompat.Builder(context, channelId);
 // If enabled, Android 8+ "colorizes" the notification color by extracting colors from the artwork
 nb.setColorized(isColorized);

iOS: the plugin does not work if cordova background mode is not enabled

Hello everybody,

I am trying to use this plugin but if I do not enable cordova background mode, it does not show the track different track info(+cover image) and the previous and next buttons are not working.

Is there a possibility to fix this because cordova background mode is stop audio of other apps and my app.

Thank you.

Is it too much to ask, an example? something simple, please =(

I mean, I've been trying to make the plugin work in my app for a few days, but I'm new to the field. And i'm trying to do something simple but unsuccessful.

please someone tell me where i am wrog...

this is my code:

<body>
<audio id="player" controls>
        <source src="music.mp3" type="audio/mp3">
</audio>

<script src="cordova.js"></script>

<script type="text/javascript">

var audioplayer = document.getElementById("player");

MusicControls.create({
  track     : 'name of track',   
  artist     : 'name o artist',          
  album   : 'name of album',   
  cover    : 'albums/album.jpg',
  playIcon: 'media_play',
  pauseIcon: 'media_pause',
  prevIcon: 'media_prev',
  nextIcon: 'media_next',
  closeIcon: 'media_close',
  notificationIcon: 'notification'
}, onSuccess, onError);

</script>
</body>

how should i proceed from here?

I'm having the error: Uncaught ReferenceError: MusicControls is not defined

Should I insert something in config.xml?

how do i reference the plugin to the music? something like: audioplayer.MusicControls.create({ ... }) ??

README installation seems wrong

I'm not the best with Node, and especially not Cordova, however it seems the suggested npm install cordova-plugin-music-controls2 installation command did not work for me, however cordova plugin add cordova-plugin-music-controls2 did work.

Notification not showing and subscription not working

I followed the docs and tried to implement this plugin with the below code but notification is not triggered in my device and subscription code is not executed.

ionViewDidEnter() {
    this.musicControls.create({
      track: 'Time is Running Out',        // optional, default : ''
      artist: 'Muse',                       // optional, default : ''
      cover: 'assets/imgs/sign3.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://...')
      isPlaying: true,                         // optional, default : true
      dismissable: true,                         // optional, default : false

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

      // iOS only, optional
      album: 'Absolution',     // optional, default: ''
      duration: 60, // optional, default: 0
      elapsed: 10, // optional, default: 0
      hasSkipForward: true,  // show skip forward button, optional, default: false
      hasSkipBackward: true, // show skip backward button, optional, default: false
      skipForwardInterval: 15, // display number for skip forward, optional, default: 0
      skipBackwardInterval: 15, // display number for skip backward, optional, default: 0
      hasScrubbing: false, // enable scrubbing from control center and lockscreen progress bar, optional

      // Android only, optional
      // text displayed in the status bar when the notification (and the ticker) are updated, optional
      ticker: 'Now playing "Time is Running Out"',
      // All icons default to their built-in android equivalents
      playIcon: 'media_play',
      pauseIcon: 'media_pause',
      prevIcon: 'media_prev',
      nextIcon: 'media_next',
      closeIcon: 'media_close',
      notificationIcon: 'notification'
    });
    this.musicControls.subscribe().subscribe(action => {
      console.log('events action: ', action);  // Not executed
      const message = JSON.parse(action).message;
      switch (message) {
        case 'music-controls-next':
          // Do something
          break;
        case 'music-controls-previous':
          // Do something
          break;
        case 'music-controls-pause':
          // Do something
          break;
        case 'music-controls-play':
          // Do something
          break;
        case 'music-controls-destroy':
          // Do something
          break;

        // External controls (iOS only)
        case 'music-controls-toggle-play-pause':
          // Do something
          break;
        case 'music-controls-seek-to':
          const seekToInSeconds = JSON.parse(action).position;
          this.musicControls.updateElapsed({
            elapsed: seekToInSeconds,
            isPlaying: true
          });
          // 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;
      }
    });
    this.musicControls.listen(); // activates the observable above
    this.musicControls.updateIsPlaying(true);
}

Random crashes updateNotification

Hi, at random times the app crashes right in the beginning, the errors that play console report are the following:
Both from the updateNotification function. Any idea? Thank you!

IMG_20200916_212142

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.