惊讶地说,这是可以实现的,我刚刚做到了。
这种方法支持所有可能性:
只要你有一个运行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];
并且 #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];
}
在您的 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];
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
}
参考资料
当应用程序在后台运行时,您可以执行此后台任务:
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
这也许可以帮到你: AVPlayer 在后台播放视频
以上的答案在应用程序进入后台时会暂停视频一秒钟,但是通过使用下面提到的方法,可以使视频在应用程序进入后台时继续播放而没有任何故障。
如果AVPlayer的当前项目正在设备的显示器上显示视频,则当应用程序被发送到后台时,AVPlayer的播放将自动暂停。有两种方法可以防止此暂停:
参考资料
您可以通过使用下面代码集来实现您的要求。
Swift: 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()
}
}
AVPlayerLayer
部分时,它可以在锁屏时播放。显然,我需要PlayerLayer才能真正看到视频。有没有办法让AVPlayerLayer
跟随AVPlayer
的流程,不会在锁定手机时停止播放? - Nerrolken