我可以惊讶地说这是可以实现的,而且我刚刚做到了。
此方法支持所有可能性:
- 屏幕被用户锁定;
- 按下主页按钮;
- 切换到其他应用程序。
只要你有一个实例AVPlayer
运行 iOS 会阻止设备自动锁定。
首先,您需要配置应用程序以支持 Info.plist 文件中的音频背景,添加UIBackgroundModes
排列audio
元素。
然后将你的AppDelegate.m放入- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:
这些方法
[[AVAudioSession sharedInstance] setDelegate: self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
and #import <AVFoundation/AVFoundation.h>
然后在你的视图控制器中控制AVPlayer
-(void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
and
- (void)viewWillDisappear:(BOOL)animated
{
[mPlayer pause];
[super viewWillDisappear:animated];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
然后回应
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
switch (event.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause:
if([mPlayer rate] == 0){
[mPlayer play];
} else {
[mPlayer pause];
}
break;
case UIEventSubtypeRemoteControlPlay:
[mPlayer play];
break;
case UIEventSubtypeRemoteControlPause:
[mPlayer pause];
break;
default:
break;
}
}
如果用户按下主页按钮,则需要另一个技巧来恢复再现(在这种情况下,再现会暂停并淡出)。
当你控制视频的再现时(我有play:
and pause:
方法)设置
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
and
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
以及要调用的相应方法,该方法将启动计时器并恢复再现。
- (void)applicationDidEnterBackground:(NSNotification *)notification
{
[mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01];
}