在我的 iPhone 应用程序中,当应用程序进入后台模式时,我想继续播放视频.
In my iPhone application I want to keep play video when application enter in background mode.
我正在使用 AVPlayer 并且没有找到任何在后台播放视频的方法.如果有人能帮助我,我将不胜感激.谢谢
I am using AVPlayer and not finding any way to play video in background. I will be very grateful if any one can help me in this. Thanks
推荐答案惊讶地我可以说这是可以实现的,而我就是这样做的.
With surprise I can say that this can be achieved and I just did it.
这个方法支持所有的可能性:
This method supports all the possibilities:
- 屏幕被用户锁定;
- 按下主页按钮;
- 切换到其他应用程序.
只要你有一个运行 iOS 的 AVPlayer 实例,就可以防止设备自动锁定.
As long as you have an instance of AVPlayer running iOS prevents auto lock of the device.
首先,您需要配置应用程序以支持来自 Info.plist 文件的音频背景,并在 UIBackgroundModes 数组中添加 audio 元素.
First you need to configure the application to support audio background from the Info.plist file adding in the UIBackgroundModes array the audio element.
然后将你的 AppDelegate.m 放入 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:
Then put in your AppDelegate.m into - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:
这些方法
[[AVAudioSession sharedInstance] setDelegate: self]; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];和 #import
然后在您的视图控制器中控制 AVPlayer
Then in your view controller that controls 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; } }如果用户按下主页按钮,则需要另一个技巧来恢复再现(在这种情况下,再现会因淡出而暂停).
Another trick is needed to resume the reproduction if the user presses the home button (in which case the reproduction is suspended with a fade out).
当你控制视频的再现时(我有play:和pause:方法)设置
When you control the reproduction of the video (I have play: and pause: methods) set
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];和
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];以及要调用的相应方法将启动计时器并恢复再现.
and the corresponding method to be invoked that will launch a timer and resume the reproduction.
- (void)applicationDidEnterBackground:(NSNotification *)notification { [mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01]; }更多推荐
使用 Avplayer 在后台播放视频
发布评论