-
Notifications
You must be signed in to change notification settings - Fork 32
/
RmxAudioPlayer.m
1444 lines (1168 loc) 路 51 KB
/
RmxAudioPlayer.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#import "RmxAudioPlayer.h"
#import "AVBidirectionalQueuePlayer.h"
static char kAvQueuePlayerContext;
static char kAvQueuePlayerRateContext;
static char kPlayerItemStatusContext;
static char kPlayerItemDurationContext;
static char kPlayerItemTimeRangesContext;
@interface RmxAudioPlayer() {
id _playbackTimeObserver;
BOOL _wasPlayingInterrupted;
BOOL _commandCenterRegistered;
BOOL _resetStreamOnPause;
NSMutableDictionary* _updatedNowPlayingInfo;
float _rate;
float _volume;
BOOL _isReplacingItems;
BOOL _isWaitingToStartPlayback;
}
@property () NSString* statusCallbackId;
@property (nonatomic, strong) AVBidirectionalQueuePlayer* avQueuePlayer;
@property (nonatomic) NSMutableArray* currentItems;
//@property (nonatomic) NSUInteger currentIndex;
@property () float rate;
@property () float volume;
@property () BOOL loop;
@property (nonatomic) BOOL isAtEnd;
@property (nonatomic) BOOL isAtBeginning;
@property (nonatomic) BOOL isPlaying;
@property (nonatomic) float estimatedDuration;
@property (nonatomic) float queuePosition;
@end
@implementation RmxAudioPlayer
- (void) pluginInitialize
{
_playbackTimeObserver = nil;
_wasPlayingInterrupted = NO;
_commandCenterRegistered = NO;
_updatedNowPlayingInfo = nil;
_resetStreamOnPause = YES;
_isReplacingItems = NO;
_isWaitingToStartPlayback = NO;
self.rate = 1.0f;
self.volume = 1.0f;
self.loop = false;
[self activateAudioSession];
[self observeLifeCycle];
}
#pragma mark - Cordova interface
/**
*
* Cordova interface
*
* These are basically just passing through to the core functionality of the queue and this player.
*
* These functions don't really do anything interesting by themselves.
*
*
*
*
*
*/
- (void) initialize:(CDVInvokedUrlCommand*) command
{
NSLog(@"RmxAudioPlayer.execute=initialize");
self.statusCallbackId = command.callbackId;
[self onStatus:RMXSTATUS_REGISTER trackId:@"INIT" param:nil];
}
- (void) setOptions:(CDVInvokedUrlCommand*) command {
NSDictionary* options = [command.arguments objectAtIndex:0];
if (options == nil) {
options = @{};
}
NSLog(@"RmxAudioPlayer.execute=setOptions, %@", options);
_resetStreamOnPause = [options[@"resetStreamOnPause"] boolValue];
// We don't do anything with these yet.
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:options];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) setPlaylistItems:(CDVInvokedUrlCommand *) command {
NSMutableArray* items = [command.arguments objectAtIndex:0];
NSDictionary* options = [command.arguments objectAtIndex:1];
if (options == nil) {
options = @{};
}
NSLog(@"RmxAudioPlayer.execute=setPlaylistItems, %@, %@", options, items);
float seekToPosition = 0.0f;
BOOL retainPosition = options[@"retainPosition"] != nil ? [options[@"retainPosition"] boolValue] : NO;
float playFromPosition = options[@"retainPosition"] != nil ? [options[@"playFromPosition"] floatValue] : 0.0f;
BOOL startPaused = options[@"startPaused"] != nil ? [options[@"startPaused"] boolValue] : YES;
if (retainPosition) {
seekToPosition = [self getTrackCurrentTime:nil];
if (playFromPosition > 0.0f) {
seekToPosition = playFromPosition;
}
}
[self.commandDelegate runInBackground:^{
// This will wait for the AVPlayerItemStatusReadyToPlay status change, and then trigger playback.
_isWaitingToStartPlayback = !startPaused;
if (_isWaitingToStartPlayback) {
NSLog(@"RmxAudioPlayer[setPlaylistItems] will wait for ready event to begin playback");
}
[self insertOrReplaceTracks:items replace:YES startPosition:seekToPosition];
if (_isWaitingToStartPlayback) {
[self playCommand:NO]; // but we will try to preempt it to avoid the button blinking paused.
}
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}];
}
- (void) addItem:(CDVInvokedUrlCommand *) command {
NSMutableDictionary* item = [command.arguments objectAtIndex:0];
NSLog(@"RmxAudioPlayer.execute=addItem, %@", item);
AudioTrack* newTrack = [AudioTrack initWithDictionary:item];
if (newTrack) {
NSMutableArray* tempArr = [NSMutableArray arrayWithObject:newTrack];
[self addTracks:tempArr];
}
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) addAllItems:(CDVInvokedUrlCommand *) command {
NSMutableArray* items = [command.arguments objectAtIndex:0];
NSLog(@"RmxAudioPlayer.execute=addAllItems, %@", items);
[self insertOrReplaceTracks:items replace:NO startPosition:-1];
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) removeItems:(CDVInvokedUrlCommand *) command {
NSMutableArray* items = [command.arguments objectAtIndex:0];
NSLog(@"RmxAudioPlayer.execute=removeItems, %@", items);
int removed = 0;
if (items != nil || items.count > 0) {
for (NSDictionary *item in items) {
NSString* trackIndex = [item objectForKey:@"trackIndex"];
NSString* trackId = [item objectForKey:@"trackId"];
if ([self removeItemWithValues:trackIndex trackId:trackId]) {
removed++;
}
}
}
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:removed];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) removeItem:(CDVInvokedUrlCommand *) command {
NSString* trackIndex = [command.arguments objectAtIndex:0];
NSString* trackId = [command.arguments objectAtIndex:1];
NSLog(@"RmxAudioPlayer.execute=removeItem, %@, %@", trackId, trackIndex);
BOOL success = [self removeItemWithValues:trackIndex trackId:trackId];
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsBool:success];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) clearAllItems:(CDVInvokedUrlCommand*) command {
NSLog(@"RmxAudioPlayer.execute=clearAllItems");
[self removeAllTracks:NO];
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) play:(CDVInvokedUrlCommand *) command {
NSLog(@"RmxAudioPlayer.execute=play");
[self playCommand:NO];
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) playTrackByIndex:(CDVInvokedUrlCommand *) command {
NSNumber* argVal = [command argumentAtIndex:0 withDefault:[NSNumber numberWithInt:0]];
NSLog(@"RmxAudioPlayer.execute=playTrackByIndex, %@", argVal);
int index = argVal.intValue;
if (index < 0 || index >= [self avQueuePlayer].itemsForPlayer.count) {
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Provided index is out of bounds"];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
} else {
[self avQueuePlayer].currentIndex = argVal.intValue;
[self playCommand:NO];
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
}
- (void) playTrackById:(CDVInvokedUrlCommand *) command {
NSString* trackId = [command.arguments objectAtIndex:0];
NSLog(@"RmxAudioPlayer.execute=playTrackById, %@", trackId);
NSDictionary* result = [self findTrackById:trackId];
NSInteger idx = [(NSNumber*)result[@"index"] integerValue];
// AudioTrack* track = result[@"track"];
if ([self avQueuePlayer].itemsForPlayer.count > 0) {
if (idx >= 0) {
[self avQueuePlayer].currentIndex = idx;
[self playCommand:NO];
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsNSUInteger:idx];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
} else {
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Track ID not found"];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
} else {
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"The playlist is empty!"];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
}
- (void) pause:(CDVInvokedUrlCommand *) command {
NSLog(@"RmxAudioPlayer.execute=pause");
_isWaitingToStartPlayback = NO;
[self pauseCommand:NO];
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) skipForward:(CDVInvokedUrlCommand *) command {
NSLog(@"RmxAudioPlayer.execute=skipForward");
[self playNext:NO];
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) skipBack:(CDVInvokedUrlCommand *) command {
NSLog(@"RmxAudioPlayer.execute=skipBack");
[self playPrevious:NO];
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) seekTo:(CDVInvokedUrlCommand *) command {
NSNumber* argVal = [command argumentAtIndex:0 withDefault:[NSNumber numberWithFloat:0.0]];
NSLog(@"RmxAudioPlayer.execute=seekTo, %@", argVal);
float positionTime = argVal.floatValue;
[self seekTo:positionTime isCommand:YES];
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) seekToQueuePosition:(CDVInvokedUrlCommand *) command {
NSNumber* argVal = [command argumentAtIndex:0 withDefault:[NSNumber numberWithFloat:0.0]];
NSLog(@"RmxAudioPlayer.execute=seekToQueuePosition, %@", argVal);
float positionTime = argVal.floatValue;
[[self avQueuePlayer] seekToTimeInQueue:CMTimeMakeWithSeconds(positionTime, NSEC_PER_SEC) completionHandler:^(BOOL complete) {
// I guess we could check if the seek actually succeeded.
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}];
}
- (void) setPlaybackRate:(CDVInvokedUrlCommand *) command {
NSNumber* argVal = [command argumentAtIndex:0 withDefault:[NSNumber numberWithFloat:1.0]];
NSLog(@"RmxAudioPlayer.execute=setPlaybackRate, %@", argVal);
self.rate = argVal.floatValue;
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) setPlaybackVolume:(CDVInvokedUrlCommand *) command {
NSNumber* argVal = [command argumentAtIndex:0 withDefault:[NSNumber numberWithFloat:self.volume]];
NSLog(@"RmxAudioPlayer.execute=setPlaybackVolume, %@", argVal);
self.volume = argVal.floatValue;
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) setLoopAll:(CDVInvokedUrlCommand *) command {
id loop2 = [command argumentAtIndex:0];
if (([loop2 isKindOfClass:[NSString class]] && [loop2 isEqualToString:@"true"]) || [loop2 boolValue]) {
self.loop = YES;
} else {
self.loop = NO;
}
NSLog(@"RmxAudioPlayer.execute=setLoopAll, %@", loop2);
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) getPlaybackRate:(CDVInvokedUrlCommand *) command {
NSLog(@"RmxAudioPlayer.execute=getPlaybackRate, %f", self.rate);
float rate = self.rate;
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:rate];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) getPlaybackVolume:(CDVInvokedUrlCommand *) command {
NSLog(@"RmxAudioPlayer.execute=getPlaybackVolume, %f", self.volume);
float volume = self.volume;
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:volume];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) getPlaybackPosition:(CDVInvokedUrlCommand *) command {
float currentPosition = [self getTrackCurrentTime:nil];
NSLog(@"RmxAudioPlayer.execute=getPlaybackPosition, %f", currentPosition);
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:currentPosition];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) getCurrentBuffer:(CDVInvokedUrlCommand *) command {
NSDictionary* trackStatus = [self getPlayerStatusItem:nil];
NSLog(@"RmxAudioPlayer.execute=getCurrentBuffer, %@", trackStatus);
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:trackStatus];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) getTotalDuration:(CDVInvokedUrlCommand *) command {
float duration = self.estimatedDuration;
NSLog(@"RmxAudioPlayer.execute=getTotalDuration, %f", duration);
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:duration];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) getQueuePosition:(CDVInvokedUrlCommand *) command {
float position = self.queuePosition;
NSLog(@"RmxAudioPlayer.execute=getQueuePosition, %f", position);
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDouble:position];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
- (void) release:(CDVInvokedUrlCommand*)command {
NSLog(@"RmxAudioPlayer.execute=release");
_isWaitingToStartPlayback = NO;
[self releaseResources];
CDVPluginResult* result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
[self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}
/* ****** */
/* Utilities for the above functions */
- (void) insertOrReplaceTracks:(NSArray*)items replace:(BOOL)replace startPosition:(float)startPosition {
if (items == nil || items.count == 0) {
return;
}
NSMutableArray* newList = [NSMutableArray arrayWithCapacity:items.count];
for (NSDictionary *item in items) {
AudioTrack* track = [AudioTrack initWithDictionary:item];
if (track) {
[newList addObject:track];
}
}
if (replace) {
[self setTracks:newList startPosition:startPosition];
} else {
[self addTracks:newList];
}
}
- (BOOL) removeItemWithValues:(NSString*)trackIndex trackId:(NSString*)trackId {
if ((id)trackIndex != [NSNull null]
&& [trackIndex integerValue] > 0
&& [trackIndex integerValue] < [self avQueuePlayer].itemsForPlayer.count
) {
AudioTrack* item = [self avQueuePlayer].itemsForPlayer[[trackIndex integerValue]];
[self removeTrackObservers:item];
[[self avQueuePlayer] removeItem:item];
return YES;
} else if ((id)trackId != [NSNull null] && ![trackId isEqualToString:@""]) {
NSDictionary* result = [self findTrackById:trackId];
NSInteger idx = [(NSNumber*)result[@"index"] integerValue];
AudioTrack* track = result[@"track"];
if (idx >= 0) {
// AudioTrack* item = [self avQueuePlayer].itemsForPlayer[idx];
[self removeTrackObservers:track];
[[self avQueuePlayer] removeItem:track];
return YES;
} else {
return NO;
}
} else {
return NO;
}
}
#pragma mark - player actions
/**
*
* Player actions.
*
* These are the public API for the player and wrap most of the complexity of the queue.
*
*
*
*
*
*
*
*/
- (void) playCommand:(BOOL)isCommand
{
_wasPlayingInterrupted = NO;
[self initializeMPCommandCenter];
// [[self avQueuePlayer] play];
if (_resetStreamOnPause) {
AudioTrack* currentTrack = (AudioTrack*)[self avQueuePlayer].currentItem;
if (currentTrack != nil && currentTrack.isStream) {
[[self avQueuePlayer] seekToTime:kCMTimePositiveInfinity toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
[currentTrack seekToTime:kCMTimePositiveInfinity toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:nil];
}
}
[self avQueuePlayer].rate = self.rate;
[self avQueuePlayer].volume = self.volume;
if (isCommand) {
NSString * action = @"music-controls-play";
NSLog(@"%@", action);
}
}
- (void) pauseCommand:(BOOL)isCommand
{
_wasPlayingInterrupted = NO;
[self initializeMPCommandCenter];
[[self avQueuePlayer] pause];
// When the track is a stream, we do not want it to hold the buffer at the current location;
// it does in fact continue buffering afterwards but the buffer on iOS is rather small, so you'll end up
// reaching a point where you jump forward in time however long you were paused.
// The correct behavior for streams is to pick up at the current LIVE point in the stream, which we accomplish
// by seeking to the "end" of the stream.
if (_resetStreamOnPause) {
AudioTrack* currentTrack = (AudioTrack*)[self avQueuePlayer].currentItem;
if (currentTrack != nil && currentTrack.isStream) {
[[self avQueuePlayer] seekToTime:kCMTimePositiveInfinity toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
[currentTrack seekToTime:kCMTimePositiveInfinity toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:nil];
}
}
if (isCommand) {
NSString * action = @"music-controls-pause";
NSLog(@"%@", action);
}
}
- (void) playPrevious:(BOOL)isCommand
{
_wasPlayingInterrupted = NO;
[self initializeMPCommandCenter];
[[self avQueuePlayer] playPreviousItem];
if (isCommand) {
NSString * action = @"music-controls-previous";
NSLog(@"%@", action);
AudioTrack* playerItem = (AudioTrack*)[self avQueuePlayer].currentItem;
NSDictionary* param = @{
@"currentIndex": @([self avQueuePlayer].currentIndex),
@"currentItem": [playerItem toDict]
};
[self onStatus:RMX_STATUS_SKIP_BACK trackId:playerItem.trackId param:param];
}
}
- (void) playNext:(BOOL)isCommand
{
_wasPlayingInterrupted = NO;
[self initializeMPCommandCenter];
[[self avQueuePlayer] advanceToNextItem];
if (isCommand) {
NSString * action = @"music-controls-next";
NSLog(@"%@", action);
AudioTrack* playerItem = (AudioTrack *)[self avQueuePlayer].currentItem;
NSDictionary* param = @{
@"currentIndex": @([self avQueuePlayer].currentIndex),
@"currentItem": [playerItem toDict]
};
[self onStatus:RMX_STATUS_SKIP_FORWARD trackId:playerItem.trackId param:param];
}
}
- (void) seekTo:(float)positionTime isCommand:(BOOL)isCommand
{
//Handle seeking with the progress slider on lockscreen or control center
_wasPlayingInterrupted = NO;
[self initializeMPCommandCenter];
CMTime seekToTime = CMTimeMakeWithSeconds(positionTime, 1000);
[[self avQueuePlayer] seekToTime:seekToTime toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
NSString * action = @"music-controls-seek-to";
NSLog(@"%@ %.3f", action, positionTime);
if (isCommand) {
AudioTrack* playerItem = (AudioTrack *)[self avQueuePlayer].currentItem;
[self onStatus:RMXSTATUS_SEEK trackId:playerItem.trackId param:@{@"position": @(positionTime)}];
}
}
- (float) rate
{
return _rate;
}
- (void) setRate:(float)rate
{
_rate = rate;
[self avQueuePlayer].rate = rate;
}
- (float) volume
{
return _volume;
}
- (void) setVolume:(float)volume
{
_volume = volume;
[self avQueuePlayer].volume = volume;
}
- (void) addTracks:(NSMutableArray<AudioTrack*>*)tracks
{
for (AudioTrack* playerItem in tracks) {
[self addTrackObservers:playerItem];
}
[[self avQueuePlayer] insertAllItems:tracks];
}
- (void) setTracks:(NSMutableArray<AudioTrack*>*)tracks startPosition:(float)startPosition
{
for (AudioTrack* item in [self avQueuePlayer].itemsForPlayer) {
[self removeTrackObservers:item];
}
for (AudioTrack* playerItem in tracks) {
[self addTrackObservers:playerItem];
}
_isReplacingItems = YES;
[[self avQueuePlayer] setItemsForPlayer:tracks];
if (startPosition > 0) {
[self seekTo:startPosition isCommand:NO];
}
}
- (void) removeAllTracks:(BOOL)isCommand
{
for (AudioTrack* item in [self avQueuePlayer].itemsForPlayer) {
[self removeTrackObservers:item];
}
[[self avQueuePlayer] removeAllItems];
_wasPlayingInterrupted = NO;
NSLog(@"RmxAudioPlayer, removeAllTracks, ==> RMXSTATUS_PLAYLIST_CLEARED");
[self onStatus:RMXSTATUS_PLAYLIST_CLEARED trackId:@"INVALID" param:nil];
// a.t.m there's no way for this to be triggered from within the plugin,
// but it might get added at some point.
if (isCommand) {
NSString * action = @"music-controls-clear";
NSLog(@"%@", action);
}
}
#pragma mark - remote control events
/**
*
* Events - receive events from the iOS remote controls and command center.
*
*
*
*
*
*
*
*
*/
- (void) playEvent:(MPRemoteCommandEvent *)event {
[self playCommand:YES];
}
- (void) pauseEvent:(MPRemoteCommandEvent *)event {
[self pauseCommand:YES];
}
- (void) togglePlayPauseTrackEvent:(MPRemoteCommandEvent *)event {
if ([self avQueuePlayer].isPlaying) {
[self pauseCommand:YES];
} else {
[self playCommand:YES];
}
}
- (void) prevTrackEvent:(MPRemoteCommandEvent *)event {
[self playPrevious:YES];
}
- (void) nextTrackEvent:(MPRemoteCommandEvent *)event {
[self playNext:YES];
}
- (MPRemoteCommandHandlerStatus) changedThumbSliderOnLockScreen:(MPChangePlaybackPositionCommandEvent *)event {
[self seekTo:event.positionTime isCommand:YES];
return MPRemoteCommandHandlerStatusSuccess;
}
#pragma mark - notifications
/**
*
* Notifications
*
* These handle the events raised by the queue and the player items.
*
*
*
*
*
*
*
*/
- (void) itemStalledPlaying:(NSNotification *) notification {
// This happens when the network is insufficient to continue playback.
AudioTrack* playerItem = (AudioTrack*)[self avQueuePlayer].currentItem;
NSDictionary* trackStatus = [self getPlayerStatusItem:playerItem];
[self onStatus:RMXSTATUS_STALLED trackId:playerItem.trackId param:trackStatus];
[self onStatus:RMXSTATUS_PAUSE trackId:playerItem.trackId param:trackStatus];
}
- (void) playerItemDidReachEnd:(NSNotification *) notification {
NSLog(@"Player item reached end: %@", notification.object);
AudioTrack* playerItem = (AudioTrack*)notification.object;
// When an item finishes, immediately scrub it back to the beginning
// so that the visual indicators show you can "play again" or whatever.
// Might make sense to have a flag for this behavior.
[playerItem seekToTime:kCMTimeZero toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:nil];
NSDictionary* trackStatus = [self getPlayerStatusItem:playerItem];
[self onStatus:RMXSTATUS_COMPLETED trackId:playerItem.trackId param:trackStatus];
}
- (void) handleAudioSessionInterruption:(NSNotification*)interruptionNotification
{
NSLog(@"Audio session interruption received: %@", interruptionNotification);
NSDictionary* userInfo = interruptionNotification.userInfo;
AVAudioSessionInterruptionType interruptionType = [userInfo[AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
switch (interruptionType) {
case AVAudioSessionInterruptionTypeBegan: {
BOOL suspended = [userInfo[AVAudioSessionInterruptionWasSuspendedKey] boolValue];
NSLog(@"AVAudioSessionInterruptionTypeBegan. Was suspended: %d", suspended);
if ([[self avQueuePlayer] isPlaying]) {
_wasPlayingInterrupted = YES;
}
// [[self avQueuePlayer] pause];
[self pauseCommand:NO];
break;
}
case AVAudioSessionInterruptionTypeEnded: {
NSLog(@"AVAudioSessionInterruptionTypeEnded");
AVAudioSessionInterruptionOptions interruptionOption = [userInfo[AVAudioSessionInterruptionOptionKey] unsignedIntegerValue];
if (interruptionOption == AVAudioSessionInterruptionOptionShouldResume) {
if (_wasPlayingInterrupted) {
[[self avQueuePlayer] play];
}
}
_wasPlayingInterrupted = NO;
break;
}
default:
break;
}
}
/*
* This method only executes while the queue is playing, so we can use the playback position event.
*/
- (void) executePeriodicUpdate:(CMTime)time {
AudioTrack *playerItem = (AudioTrack *)[self avQueuePlayer].currentItem;
if (!CMTIME_IS_INDEFINITE(playerItem.currentTime)) {
[self updateNowPlayingTrackInfo:playerItem updateTrackData:NO];
NSDictionary* trackStatus = [self getPlayerStatusItem:playerItem];
[self onStatus:RMXSTATUS_PLAYBACK_POSITION trackId:playerItem.trackId param:trackStatus];
// NSLog(@" . %.5f / %.5f sec (%.1f %%) [%@]", currentTime, duration, (currentTime / duration)*100.0, name);
}
return;
}
- (void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"currentItem"] && context == &kAvQueuePlayerContext)
{
AVBidirectionalQueuePlayer *player = (AVBidirectionalQueuePlayer *)object;
AudioTrack *playerItem = (AudioTrack *)player.currentItem;
[self handlePlayerCurrentItemChanged:playerItem];
return;
}
if ([keyPath isEqualToString:@"rate"] && context == &kAvQueuePlayerRateContext)
{
AVBidirectionalQueuePlayer *player = (AVBidirectionalQueuePlayer *)object;
AudioTrack *playerItem = (AudioTrack *)player.currentItem;
if (playerItem == nil) {
return;
}
NSDictionary* trackStatus = [self getPlayerStatusItem:playerItem];
NSLog(@"Playback rate changed: %f, is playing: %d", player.rate, player.isPlaying);
if (player.isPlaying) {
[self onStatus:RMXSTATUS_PLAYING trackId:playerItem.trackId param:trackStatus];
} else {
[self onStatus:RMXSTATUS_PAUSE trackId:playerItem.trackId param:trackStatus];
}
return;
}
if ([keyPath isEqualToString:@"status"] && context == &kPlayerItemStatusContext)
{
AudioTrack *playerItem = (AudioTrack *)object;
[self handleTrackStatusEvent:playerItem];
return;
}
if ([keyPath isEqualToString:@"duration"] && context == &kPlayerItemDurationContext)
{
AudioTrack *playerItem = (AudioTrack *)object;
[self handleTrackDuration:playerItem];
return;
}
if ([keyPath isEqualToString:@"loadedTimeRanges"] && context == &kPlayerItemTimeRangesContext)
{
AudioTrack *playerItem = (AudioTrack *)object;
[self handleTrackBuffering:playerItem];
return;
}
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
return;
}
- (void) updateNowPlayingTrackInfo:(AudioTrack*)playerItem updateTrackData:(BOOL)updateTrackData
{
AudioTrack* currentItem = playerItem;
if (currentItem == nil) {
currentItem = (AudioTrack*)[self avQueuePlayer].currentItem;
}
MPNowPlayingInfoCenter* nowPlayingInfoCenter = [MPNowPlayingInfoCenter defaultCenter];
if (_updatedNowPlayingInfo == nil) {
NSDictionary* nowPlayingInfo = nowPlayingInfoCenter.nowPlayingInfo;
_updatedNowPlayingInfo = [NSMutableDictionary dictionaryWithDictionary:nowPlayingInfo];
}
for (NSString* val in _updatedNowPlayingInfo.allKeys) {
NSLog(@"%@ ==> %@", val, _updatedNowPlayingInfo[val]);
}
float currentTime = CMTimeGetSeconds(currentItem.currentTime);
float duration = CMTimeGetSeconds(currentItem.duration);
if (CMTIME_IS_INDEFINITE(currentItem.duration)) {
duration = 0;
}
if (updateTrackData) {
_updatedNowPlayingInfo[MPMediaItemPropertyArtist] = currentItem.artist;
_updatedNowPlayingInfo[MPMediaItemPropertyTitle] = currentItem.title;
_updatedNowPlayingInfo[MPMediaItemPropertyAlbumTitle] = currentItem.album;
}
_updatedNowPlayingInfo[MPMediaItemPropertyPlaybackDuration] = [NSNumber numberWithFloat:duration];
_updatedNowPlayingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime] = [NSNumber numberWithFloat:currentTime];
_updatedNowPlayingInfo[MPNowPlayingInfoPropertyPlaybackRate] = [NSNumber numberWithFloat:1.0];
nowPlayingInfoCenter.nowPlayingInfo = _updatedNowPlayingInfo;
MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
[commandCenter.nextTrackCommand setEnabled:!self.isAtEnd];
[commandCenter.previousTrackCommand setEnabled:!self.isAtBeginning];
}
- (void) handlePlayerCurrentItemChanged:(AudioTrack*)playerItem
{
NSLog(@"Queue changed current item to: %@", [playerItem toDict]);
// NSLog(@"New music name: %@", ((AVURLAsset*)playerItem.asset).URL.pathComponents.lastObject);
NSLog(@"New item ID: %@", playerItem.trackId);
NSLog(@"Queue is at end: %@", self.isAtEnd ? @"YES" : @"NO");
if (playerItem != nil) {
// When an item starts, immediately scrub it back to the beginning
[playerItem seekToTime:kCMTimeZero toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:nil];
// Update the command center
[self updateNowPlayingTrackInfo:playerItem updateTrackData:YES];
}
NSDictionary* info = @{
@"currentItem": playerItem != nil ? [playerItem toDict] : @{},
@"currentIndex": @([self avQueuePlayer].currentIndex),
@"isAtEnd": @(self.isAtEnd),
@"isAtBeginning": @(self.isAtBeginning),
@"hasNext": @(!self.isAtEnd),
@"hasPrevious": @(!self.isAtBeginning)
};
NSString* trackId = playerItem != nil ? playerItem.trackId : @"NONE";
[self onStatus:RMXSTATUS_TRACK_CHANGED trackId:trackId param:info];
if ([[self avQueuePlayer] isAtEnd] && [self avQueuePlayer].currentItem == nil) {
[[self avQueuePlayer] seekToTime:kCMTimeZero toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero];
if ([self avQueuePlayer].itemsForPlayer.count > 0 && !_isReplacingItems) {
[self onStatus:RMXSTATUS_PLAYLIST_COMPLETED trackId:@"INVALID" param:nil];
}
if (self.loop && [self avQueuePlayer].itemsForPlayer.count > 0) {
[[self avQueuePlayer] play];
} else {
[self onStatus:RMXSTATUS_STOPPED trackId:@"INVALID" param:nil];
}
}
}
- (void) handleTrackStatusEvent:(AudioTrack*)playerItem
{
// NSString* name = ((AVURLAsset*)playerItem.asset).URL.pathComponents.lastObject;
NSString* name = playerItem.trackId;
AVPlayerItemStatus status = playerItem.status;
// Switch over the status
switch (status) {
case AVPlayerItemStatusReadyToPlay: {
NSLog(@"PlayerItem status changed to AVPlayerItemStatusReadyToPlay [%@]", name);
NSDictionary* trackStatus = [self getPlayerStatusItem:playerItem];
[self onStatus:RMXSTATUS_CANPLAY trackId:playerItem.trackId param:trackStatus];
if (_isWaitingToStartPlayback) {
_isWaitingToStartPlayback = NO;
NSLog(@"RmxAudioPlayer[setPlaylistItems] is beginning playback after waiting for ReadyToPlay event");
[self playCommand:NO];
}
break;
}
case AVPlayerItemStatusFailed: {
// Failed. Examine AVPlayerItem.error
_isWaitingToStartPlayback = NO;
NSString* errorMsg = @"";
if (playerItem.error) {
errorMsg = [NSString stringWithFormat:@"Error playing audio track: %@", [playerItem.error localizedFailureReason]];
}
NSLog(@"AVPlayerItemStatusFailed: Error playing audio track: %@", errorMsg);
NSDictionary* errorParam = [self createErrorWithCode:RMXERR_DECODE message:errorMsg];
[self onStatus:RMXSTATUS_ERROR trackId:playerItem.trackId param:errorParam];
break;
}
case AVPlayerItemStatusUnknown:
_isWaitingToStartPlayback = NO;
NSLog(@"PlayerItem status changed to AVPlayerItemStatusUnknown [%@]", name);
// Not ready
break;
default:
break;
}
}
- (void) handleTrackDuration:(AudioTrack*)playerItem
{
// This function isn't all that useful really in terms of state management.
// It doesn't always fire, and it is not needed because the queue's periodic update can also
// deliver this info.
//NSString* name = ((AVURLAsset*)playerItem.asset).URL.pathComponents.lastObject;
NSString* name = playerItem.trackId;
if (!CMTIME_IS_INDEFINITE(playerItem.duration)) {
float duration = CMTimeGetSeconds(playerItem.duration);
NSLog(@"The track duration was changed [%@]: %f", name, duration);
// We will still report the duration though.
NSDictionary* trackStatus = [self getPlayerStatusItem:playerItem];
[self onStatus:RMXSTATUS_DURATION trackId:playerItem.trackId param:trackStatus];
} else {
NSLog(@"Item duration is indefinite (unknown): %@", ((AVURLAsset*)playerItem.asset).URL);
}
}
- (void) handleTrackBuffering:(AudioTrack*)playerItem
{
//NSString* name = ((AVURLAsset*)playerItem.asset).URL.pathComponents.lastObject;
NSString* name = playerItem.trackId;
NSDictionary* trackStatus = [self getPlayerStatusItem:playerItem];
NSLog(@" . . . %.5f -> %.5f (%.1f %%) [%@]",
[trackStatus[@"bufferStart"] floatValue],
[trackStatus[@"bufferStart"] floatValue] + [trackStatus[@"bufferEnd"] floatValue],
[trackStatus[@"bufferPercent"] floatValue], name);
[self onStatus:RMXSTATUS_BUFFERING trackId:playerItem.trackId param:trackStatus];
if ([trackStatus[@"bufferPercent"] floatValue] >= 100.0) {
[self onStatus:RMXSTATUS_LOADED trackId:playerItem.trackId param:trackStatus];
}
}
/**
*