Ema*_*uel 7 video background avplayer ios5
好的,所以我的应用程序播放视频,我希望声音继续在后台播放.但是当我点击"Home"按钮时播放停止.我正在使用iOS 5.0.1测试iPhone 4s
什么工作?
怎么了?
我做了什么:
在app delegate的应用程序中添加了以下代码:didFinishLaunchingWithOptions:
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
Run Code Online (Sandbox Code Playgroud)
在我的视图控制器中,我实现了接收远程控件的方法:
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
//End recieving events
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent {
if (receivedEvent.type == UIEventTypeRemoteControl) {
switch (receivedEvent.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause:
[self play:nil];
break;
case UIEventSubtypeRemoteControlPreviousTrack:
[self actionPlaybackPreviousItem];
break;
case UIEventSubtypeRemoteControlNextTrack:
[self actionPlaybackNextItem];
break;
default:
break;
}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么一切都有效但是,这个?
Stack Overflow 的响应能力每次都变得越来越差……希望这对每个人来说都没有那么糟糕。我没有找到任何回应,为什么视频在点击主页按钮后暂停,但是,我提供了一个解决方法,如果它对任何人有帮助的话:
由于播放器一直在播放直到应用程序进入后台,因此我创建了一个计时器,以检查应用程序在前台时是否正在播放,如果是,则恢复播放:
- (void)applicationWillResignActive:(UIApplication *)application
{
MainViewController* mainController=self.viewController;
playerWasPlaying=mainController.player.rate!=0;
}
-(void)resumePlayback {
MainViewController* mainController=self.viewController;
if (mainController.player.rate==0&&playerWasPlaying)
[mainController play:nil];
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(resumePlayback) userInfo:nil repeats:NO];
}
Run Code Online (Sandbox Code Playgroud)
在我看来,这不是最好的选择,但目前它正在工作,在恢复时播放有点跳跃。