如何使用 AVPlayer 在后台继续播放视频?

问题描述 投票:0回答:6

在我的iPhone应用程序中,我想在应用程序进入不再处于前台时继续播放视频。

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

ios video background avplayer
6个回答
19
投票

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

此方法支持所有可能性:

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

只要您有一个运行 iOS 的

AVPlayer
实例,就会阻止设备自动锁定。

首先,您需要配置应用程序以支持 Info.plist 文件中的音频背景,并在

UIBackgroundModes
数组中添加
audio
元素。

然后将你的AppDelegate.m放入

- (BOOL)application:(UIApplication *)application 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;
    }
}

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

当你控制视频的再现时(我有

play:
pause:
方法)设置

[[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];
}

1
投票

在您的

applicationDidEnterBackground
中尝试此代码:

UIApplication *app = [UIApplication sharedApplication]; 
bgTask = 0;

backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(backgroundTask) userInfo:nil repeats:YES];

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ 
[app endBackgroundTask:bgTask];

我在堆栈的某个地方找到了它 对我有用

另请查看本教程,其中涵盖了包括背景音频在内的背景模式。 http://www.raywenderlich.com/29948/backgrounding-for-ios


0
投票

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

1> 音频
2> 地点
3> 网络电话
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

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


0
投票

当应用程序进入后台时,上述答案会暂停视频一秒钟,但是通过使用下面提到的方法,它可以在应用程序进入后台时保持视频播放,没有任何故障。

如果 AVPlayer 的当前项目正在设备显示屏上显示视频,则当应用程序发送到后台时,AVPlayer 的播放会自动暂停。 有两种方法可以防止这种暂停:

  1. 禁用播放器项目中的视频轨道(仅限基于文件的内容)。
  2. 从关联的 AVPlayer 中删除 AVPlayerLayer(将 AVPlayerLayer 播放器属性设置为 nil)。

参考

在 iOS 上使用 AV Foundation 在后台播放媒体


0
投票

您可以使用以下几组代码来实现您的要求。

斯威夫特:4.2

只需创建

UIViewController

的子类
import UIKit
import AVFoundation

class VideoPlayer:UIViewController{
    var avPlayer: AVPlayer!
    var avPlayerLayer: AVPlayerLayer!
    var paused: Bool = false

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        view.backgroundColor = .clear
        avPlayer?.play()
        paused = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let theURL = Bundle.main.url(forResource:"VIDEO_NAME", withExtension: "VIDEO_TYPE") //VIDEO_TYPE -> MP4

        avPlayer = AVPlayer(url: theURL!)
        avPlayerLayer = AVPlayerLayer(player: avPlayer)
        avPlayerLayer.videoGravity = AVLayerVideoGravity.resizeAspectFill
        avPlayer.volume = 0
        avPlayer.actionAtItemEnd = .none

        avPlayerLayer.frame = view.layer.bounds
        view.backgroundColor = .clear
        view.layer.insertSublayer(avPlayerLayer, at: 0)

        addPlayerNotifications()
    }

    deinit {
        removePlayerNotifations()
    }

    func addPlayerNotifications() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(playerItemDidReachEnd(notification:)),
                                               name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
                                               object: avPlayer.currentItem)
        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
    }

    func removePlayerNotifations() {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: nil)
        NotificationCenter.default.removeObserver(self, name:UIApplication.willEnterForegroundNotification, object: nil)
        NotificationCenter.default.removeObserver(self, name:UIApplication.didEnterBackgroundNotification, object: nil)
    }

    @objc func playerItemDidReachEnd(notification: Notification) {
        let p: AVPlayerItem = notification.object as! AVPlayerItem
        p.seek(to: CMTime.zero)
    }


    //App enter in forground.
    @objc func applicationWillEnterForeground(_ notification: Notification) {
        paused = false
        avPlayer?.play()
    }

    //App enter in forground.
    @objc func applicationDidEnterBackground(_ notification: Notification) {
        paused = true
        avPlayer?.pause()
    }

    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        avPlayer.pause()
        paused = true
    }
}

现在,差不多完成了。只需使用如下子类创建

UIViewcontroller
类即可。

class Classname: VideoPlayer{
   override func viewDidLoad() {
        super.viewDidLoad()
    }
}

0
投票

在 viewDidLoad 中将 AVAudioSession 类别设置为 .playback 模式

let audioSession = AVAudioSession.sharedInstance()
do {
     try audioSession.setCategory(.playback, mode: .moviePlayback, options: [])
} catch {
     print("Failed to set audio session category.")
}

添加通知观察者

NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)

//App enter in forground.
@objc func applicationWillEnterForeground(_ notification: Notification) {
    // Reconnect the AVPlayer to the presentation when returning to the foreground

    // If presenting video with AVPlayerViewController
    playerViewController.player = player

    // If presenting video with AVPlayerLayer
    playerLayer.player = player
}

//App enter in foreground.
@objc func applicationDidEnterBackground(_ notification: Notification) {
    // Disconnect the AVPlayer from the presentation when entering background

    // If presenting video with AVPlayerViewController
    playerViewController.player = nil

    // If presenting video with AVPlayerLayer
    playerLayer.player = nil
}

参考文献

在后台播放视频资源中的音频

AVAudioSession

© www.soinside.com 2019 - 2024. All rights reserved.