我的应用程序分为两个模块。对于第一个模块,即使在屏幕锁定之后,音频也应该播放并且锁定的屏幕应该显示与媒体内容相关的详细信息。但是,在第二个模块中没有特殊要求。屏幕锁定后应立即停止音频,并且在锁定的屏幕上不应显示任何控件。
对于第一个模块,我编写了以下代码
在我的 appdelegate 中,我实现了:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
MPRemoteCommandCenter *rcc = [MPRemoteCommandCenter sharedCommandCenter];
[[rcc skipForwardCommand] setEnabled:NO];
[[rcc skipBackwardCommand] setEnabled:NO];
[[rcc nextTrackCommand] setEnabled:NO];
[[rcc previousTrackCommand] setEnabled:NO];
[[rcc skipForwardCommand] setEnabled:NO];
[[rcc skipBackwardCommand] setEnabled:NO];
rcc.playCommand.enabled = YES;
rcc.pauseCommand.enabled = YES;
[[MPRemoteCommandCenter sharedCommandCenter].playCommand addTarget:self action:@selector(play)];
[[MPRemoteCommandCenter sharedCommandCenter].pauseCommand addTarget:self action:@selector(pause)];
}
- (void) play {
[[MyVideoController instance] play];
}
- (void) pause {
[[MyVideoController instance] pause];
}
在 MyVideoController 类中
AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:url options:nil];
AVPlayerItem *playerItem = [AVPlayerItem playerItemWithAsset:avAsset];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
NSError *activationError = nil;
BOOL success = [[AVAudioSession sharedInstance] setActive: YES error: &activationError];
NSMutableDictionary *songInfo = [[NSMutableDictionary alloc] init];
MPMediaItemArtwork *albumArt = [[MPMediaItemArtwork alloc] initWithImage: [UIImage imageNamed:@"Audio_Thumbnail_Play"]];
[songInfo setObject:title forKey:MPMediaItemPropertyTitle];
[songInfo setObject:@"duration" forKey:MPMediaItemPropertyPlaybackDuration];
[songInfo setObject:albumArt forKey:MPMediaItemPropertyArtwork];
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songInfo];
self.avPlayer = [AVPlayer playerWithPlayerItem:playerItem];
self.avPlayerLayer = [AVPlayerLayer playerLayerWithPlayer:self.avPlayer];
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionModeDefault error: nil];
}
在屏幕锁定时,我看到了预期的控制器。一切都很好。
但是,在我的第二个模块中,我更改了音频会话属性 -
-(void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionModeDefault error:nil];
[session setActive:NO error:nil];
}
每当播放视频并锁定屏幕时,我都会看到下图 1 或 2 秒,然后它就消失了!可能是因为应用程序突然意识到屏幕被锁定,然后决定隐藏控件。
我相信,我一开始就不应该看到这个屏幕。除了我已经实现的之外,还有其他方法可以禁用屏幕吗?
编辑1:
在 MyVideoController 类中添加了以下部分
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:nil];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionModeDefault error: nil];
}
再次,在屏幕消失之前看到屏幕 1 秒钟。