此方法支持所有可能性:
只要您有运行 AVPlayer 实例,iOS 将防止设备自动锁定。
首先,您需要从 Info.plist 文件配置应用程序以支持后台音频,在 UIBackgroundModes 数组中添加音频元素。
然后将这些方法放入您的 AppDelegate.m 中的
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:
[[AVAudioSession sharedInstance] setDelegate: self]
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]
而且 #import <AVFoundation/AVFoundation.h>
然后在控制AVPlayer的视图控制器中使用。
-(void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
和
- (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;
}
}
如果用户按下主页按钮(此时播放会被暂停并淡出),需要另一个技巧来恢复播放。
当您控制视频的播放(我有播放方法)时,请设置
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil]
以及相应的方法将被调用,以启动计时器并恢复播放。
- (void)applicationDidEnterBackground:(NSNotification *)notification
{
[mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01];
}
我在后台播放视频时成功了,感谢大家。