在我的 iPhone 应用程序中,我想在应用程序进入后台模式时继续播放视频。
我正在使用 AVPlayer 并没有找到任何在后台播放视频的方法。如果有人能在这方面帮助我,我将不胜感激。谢谢
在我的 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];
和#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];
我发现它在堆栈的某个地方对我有用
另请查看本教程,其中涵盖背景模式,包括背景音频.. http://www.raywenderlich.com/29948/backgrounding-for-ios
当应用程序处于后台时,您可以执行此后台任务:
1> 音频
2> 位置
3> voip
4> newsstand-content
5> external-accessory
6> bluetooth-central
7> bluetooth-peripheral
看到这个链接,
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
当应用程序进入后台时,上述答案会暂停视频一秒钟,但是通过使用下面提到的方法,它可以在应用程序进入后台时保持视频播放而不会出现任何故障。
如果 AVPlayer 的当前项目正在设备显示屏上显示视频,则当应用程序被发送到后台时,AVPlayer 的播放会自动暂停。有两种方法可以防止这种暂停:
参考
在 viewDidLoad中将 AVAudioSession类别设置为.playback模式
let audioSession = AVAudioSession.sharedInstance()
do {
try audioSession.setCategory(.playback, mode: .moviePlayback, options: [])
} catch {
print("Failed to set audio session category.")
}
添加NotificationObservers
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
}
参考
您可以使用以下代码集来满足您的要求。
斯威夫特: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()
}
}