使用 Avplayer 在后台播放视频

2024-07-03

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

我正在使用 AVPlayer,但没有找到任何在后台播放视频的方法。如果有人能在这方面帮助我,我将非常感激。 谢谢


我可以惊讶地说这是可以实现的,而且我刚刚做到了。

此方法支持所有可能性:

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

只要你有一个实例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];

and #import <AVFoundation/AVFoundation.h>

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

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    [self becomeFirstResponder];
}

and

- (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;
    }
}

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

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

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];

and

[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];

以及要调用的相应方法,该方法将启动计时器并恢复再现。

- (void)applicationDidEnterBackground:(NSNotification *)notification
{
    [mPlayer performSelector:@selector(play) withObject:nil afterDelay:0.01];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Avplayer 在后台播放视频 的相关文章

随机推荐