避免多次调用会出现问题,可以在页面appear的时候填入方法,以下仅是示例
调用:
- (instancetype)init {
if ([super init]) {
[self addUI];
[self setupLockScreenControlInfo];
}
return self;
}
方法:
- (void)setupLockScreenControlInfo {
MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
// 播放和暂停按钮(耳机控制)
MPRemoteCommand *playPauseCommand = commandCenter.togglePlayPauseCommand;
playPauseCommand.enabled = YES;
[playPauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
if (self.isPlaying) {
[self pause];
}else {
[self play];
}
return MPRemoteCommandHandlerStatusSuccess;
}];
// 上一曲
MPRemoteCommand *previousCommand = commandCenter.previousTrackCommand;
[previousCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
[self previous];
return MPRemoteCommandHandlerStatusSuccess;
}];
// 下一曲
MPRemoteCommand *nextCommand = commandCenter.nextTrackCommand;
nextCommand.enabled = YES;
[nextCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
if (self.isPlaying) {
[self stop];
}
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self next];
});
return MPRemoteCommandHandlerStatusSuccess;
}];
// 拖动进度条
if (@available(iOS 9.1, *)) {
MPRemoteCommand *changePlaybackPositionCommand = commandCenter.changePlaybackPositionCommand;
changePlaybackPositionCommand.enabled = YES;
[changePlaybackPositionCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
MPChangePlaybackPositionCommandEvent *positionEvent = (MPChangePlaybackPositionCommandEvent *)event;
NSTimeInterval positionTime = positionEvent.positionTime;
[self.player seekTo:CMTimeMake(positionTime, 1)];
if (!self.isPlaying) {
[self play];
}
return MPRemoteCommandHandlerStatusSuccess;
}];
}
}