解决方法
令我惊讶的是,我可以说这可以实现,我只是做到了.
>用户锁定的屏幕;
>按下主页按钮;
>切换到其他应用程序.
只要你有一个运行iOS的AVPlayer实例就可以防止设备自动锁定.
首先,您需要配置应用程序以支持Info.plist文件中的音频背景,并在UIBackgroundModes数组中添加audio元素.
然后将您的AppDelegate.m放入 – (BOOL)应用程序:(UIApplication *)应用程序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];
和
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
以及将启动计时器并恢复再现的相应方法.
- (void)applicationDidEnterBackground:(NSNotification *)notification { [mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01]; }