beginReceivingRemoteControlEvents不会触发Apple Music的事件

8
我正在我的应用程序中播放Apple Music,苹果音乐播放器的代码如下 -
-(void) submitAppleMusicTrackWithProductID: (NSString *) productID // productID in US is the last numbers after i= in the share URL from Apple Music
{

    [SKCloudServiceController requestAuthorization:^(SKCloudServiceAuthorizationStatus status) {
        NSLog(@"status is %ld", (long)status);
        SKCloudServiceController *cloudServiceController;
        cloudServiceController = [[SKCloudServiceController alloc] init];
        [cloudServiceController requestCapabilitiesWithCompletionHandler:^(SKCloudServiceCapability capabilities, NSError * _Nullable error) {
            NSLog(@"%lu %@", (unsigned long)capabilities, error);

            if (capabilities >= SKCloudServiceCapabilityAddToCloudMusicLibrary || capabilities==SKCloudServiceCapabilityMusicCatalogPlayback)
            {
                NSLog(@"You CAN add to iCloud!");
                [[MPMediaLibrary defaultMediaLibrary] addItemWithProductID:productID completionHandler:^(NSArray<__kindof MPMediaEntity *> * _Nonnull           entities, NSError * _Nullable error)
                 {
                     NSLog(@"added id%@ entities: %@ and error is %@", productID, entities, error);
                     NSArray *tracksToPlay = [NSArray arrayWithObject:productID];
                 [[MPMusicPlayerController applicationMusicPlayer] setQueueWithStoreIDs:tracksToPlay];
                    [[MPMusicPlayerController applicationMusicPlayer] stop];
                 [[MPMusicPlayerController applicationMusicPlayer] play];
                   self.isTrackChangedByNextPreviousButton = NO;

        [[NSNotificationCenter defaultCenter]removeObserver:self name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification object:nil];
        [[NSNotificationCenter defaultCenter]removeObserver:self name:MPMusicPlayerControllerPlaybackStateDidChangeNotification object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                              selector:@selector(handleTrackChanged:)
                                                                  name:MPMusicPlayerControllerNowPlayingItemDidChangeNotification
                                                                object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                              selector:@selector(handlePlaybackStateChanged:)
                                                                  name:MPMusicPlayerControllerPlaybackStateDidChangeNotification
                                                                object:nil];


                     [[MPMusicPlayerController applicationMusicPlayer] beginGeneratingPlaybackNotifications];
                     [[MPMusicPlayerController applicationMusicPlayer] setRepeatMode: MPMusicRepeatModeNone];
                 }];


            }
            else
            {
                NSLog(@"Blast! The ability to add Apple Music track is not there. sigh.");
            }

        }];

    }];
}

-(void)handleTrackChanged:(id )notification
{
    if (!self.AppleMusicPreviuosTrack)
    {        
        self.AppleMusicPreviuosTrack = [[Tracks alloc] init];
    }
    if (self.AppleMusicPreviuosTrack.trackId == self.CurrentTrack.trackId && [MPMusicPlayerController applicationMusicPlayer].currentPlaybackRate == 0 && !self.isSongChangedManually)
    {
        self.isSongChangedManually = YES;
        [self FilterArtistsTracks:@"next" :^(Tracks *track, NSError *err)
         {

         }];

    }
    else
    {
     if ([[MPMusicPlayerController applicationMusicPlayer] currentPlaybackRate]==1)
     {
    self.AppleMusicPreviuosTrack.trackId = self.CurrentTrack.trackId;
    [[NSNotificationCenter defaultCenter] postNotificationName:kTrackChanged object:nil];
         //Delay execution of my block for 20 seconds.
 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 30 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
     self.isSongChangedManually = NO;
 });

     }
    }
}

-(void)handlePlaybackStateChanged:(id )notification
{
    NSLog(@"handle_PlaybackStateChanged");
     [[NSNotificationCenter defaultCenter] postNotificationName:kDidTrackPlaybackStatus object:nil];
    if ([MPMusicPlayerController applicationMusicPlayer].currentPlaybackRate>0)
    {
        [self.playerMenuView.playpauseButton setImage:[UIImage imageNamed:@"pause"] forState:UIControlStateNormal];
    }
    else
    {
        [self.playerMenuView.playpauseButton setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
    }

}

现在它很好用。现在我想从锁屏界面控制音轨,为此我在viewWillAppear中编写了以下代码。

  [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
   [APP_DELEGATE becomeFirstResponder];

remoteControlReceivedWithEvent方法编写在AppDelegate文件中,如下所示 -

-(void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    switch (event.subtype)
    {
        case UIEventSubtypeRemoteControlTogglePlayPause:
            [APP_DELEGATE PlayPauseMusic:nil];
            //[streamer pause];
            break;
        case UIEventSubtypeRemoteControlPlay:
            [APP_DELEGATE PlayPauseMusic:nil];
            //[streamer start];
            break;
        case UIEventSubtypeRemoteControlPause:
            [APP_DELEGATE PlayPauseMusic:nil];
            //[streamer pause];
            break;
        case UIEventSubtypeRemoteControlStop:
            [APP_DELEGATE PlayPauseMusic:nil];

            //[streamer stop];
            break;
        case UIEventSubtypeRemoteControlNextTrack:

            [APP_DELEGATE next:nil];

            break;
        case UIEventSubtypeRemoteControlPreviousTrack:
            [APP_DELEGATE previous:nil];


            break;

        default:
            break;
    }
}

注意 - remoteControlReceivedWithEvent方法会在AVPlayer播放音轨或者Spotify iOS SDK播放Spotify音轨时被触发。

但是当通过Apple Music播放音轨时,同样的代码不会被触发。

[MPMusicPlayerController applicationMusicPlayer]      

                 or

 [MPMusicPlayerController systemMusicPlayer]

任何帮助都将不胜感激。谢谢。

也在试图弄清楚这个! - evenodd
嘿,你找到解决方案了吗? - Naman Vaishnav
1个回答

0

不要使用-(void)remoteControlReceivedWithEvent:(UIEvent *)event来跟踪控件,而是使用MPRemoteCommandCenter为每个控件添加目标:

注意:在分配目标之前启用控件非常重要。

[MPRemoteCommandCenter sharedCommandCenter].playCommand.enabled = YES;
[[MPRemoteCommandCenter sharedCommandCenter].playCommand addTarget:self action:@selector(remotePlay)];

[MPRemoteCommandCenter sharedCommandCenter].pauseCommand.enabled = YES;
[[MPRemoteCommandCenter sharedCommandCenter].pauseCommand addTarget:self action:@selector(remoteStop)];

[MPRemoteCommandCenter sharedCommandCenter].previousTrackCommand.enabled = YES;
[[MPRemoteCommandCenter sharedCommandCenter].previousTrackCommand addTarget:self action:@selector(loadPreviousSong)];

[MPRemoteCommandCenter sharedCommandCenter].nextTrackCommand.enabled = YES;
[[MPRemoteCommandCenter sharedCommandCenter].nextTrackCommand addTarget:self action:@selector(loadNextSong)];

选择器:

-(void) remotePlay {
    [APP_DELEGATE PlayPauseMusic:nil];
}
-(void) remoteStop {
    [APP_DELEGATE PlayPauseMusic:nil];
}
-(void) loadNextSong {
    [APP_DELEGATE next:nil];
}
-(void) loadPreviousSong {
    [APP_DELEGATE previous:nil];
}

在使用 MPMusicPlayerController 时,你调用了这些函数吗?我无法让它触发。 - evenodd
尝试使用以下代码将您的ViewController设置为第一响应者:-(BOOL)canBecomeFirstResponder{return true;} - Pau Senabre
尝试过了,但我要再试一次。我只是想确保你实际上已经让它工作了。 - evenodd
我已经使用了这些功能,但在我的应用程序中无法正常工作。 - Anupam Mishra
我已经向苹果提交了一个错误报告。有其他的想法吗? - evenodd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接