使用Avplayer在后台播放视频

时间:2013-03-15 06:17:06

标签: ios video background avplayer

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

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

6 个答案:

答案 0 :(得分:17)

令人惊讶的是,我可以说这可以实现,我就是这样做的。

此方法支持所有可能性:

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

只要您拥有运行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 :(得分:0)

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

1&GT;音频
2 - ;位置
3 GT; VOIP
4&GT;报刊亭内容
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 play video in background

答案 2 :(得分:0)

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

答案 3 :(得分:0)

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

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

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

    参考

         

    Playing media while in the background using AV Foundation on iOS

答案 4 :(得分: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
    }
}

现在,Almoast完成了。只需使用以下子类创建UIViewcontroller类即可。

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

答案 5 :(得分: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
}

参考资料

Playing Audio from a Video Asset in the Background,

AVAudioSession