使用Avplayer在后台播放视频

S S*_*S S 9 video background ios avplayer

在我的iPhone应用程序中,我想在应用程序进入后台模式时继续播放视频.

我正在使用AVPlayer而没有找到任何方式在后台播放视频.如果有人能帮助我,我将非常感激.谢谢

Mac*_*Teo 17

令我惊讶的是,我可以说这可以实现,我只是做到了.

此方法支持所有可能性:

  • 屏幕由用户锁定;
  • 按下主页按钮;
  • 切换到其他应用程序.

只要你有一个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];
Run Code Online (Sandbox Code Playgroud)

#import <AVFoundation/AVFoundation.h>

然后在您控制的视图控制器中 AVPlayer

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}
Run Code Online (Sandbox Code Playgroud)

- (void)viewWillDisappear:(BOOL)animated
{
    [mPlayer pause];    
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
    [self resignFirstResponder];
}
Run Code Online (Sandbox Code Playgroud)

然后回应

- (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;
    }
}
Run Code Online (Sandbox Code Playgroud)

如果用户按下主页按钮,则需要另一个技巧来恢复再现(在这种情况下,再现以淡出暂停).

当您控制视频的再现(我有play:pause:方法)设置

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
Run Code Online (Sandbox Code Playgroud)

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
Run Code Online (Sandbox Code Playgroud)

以及将启动计时器并恢复再现的相应方法.

- (void)applicationDidEnterBackground:(NSNotification *)notification
{
    [mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01];
}
Run Code Online (Sandbox Code Playgroud)


Ban*_*tal 0

当应用程序处于后台时,您可以执行此后台任务:

1> 音频
2> 位置
3> VoIP
4> 报亭内容
5> 外部配件
6> 蓝牙中央
7> 蓝牙外设
请参阅此链接,

http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html
http://www.rideitdown.com/2012/10/how-to-listen-youtube-videos-in.html
Run Code Online (Sandbox Code Playgroud)

这也可能对您有帮助: AVPlayer 在后台播放视频