中,添加 UIBackGroundModes ,可以添加包括 Audio 在后台播放音频和视频里的声音,location 保持当前用户的位置信息, voip 使用网络电话。添加以上字段是为了通知系统框架,在应用程序进入后台时候请求在后台继续播放一段时间,具体播放多久,根据 UIBackGroundTask 去申请一段时间。还可以使用本地通知,预先设定 local notification 来让应用程序在后台运行。
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
2. 视频
1> AVPlayer
iOS 里面视频播放用到的是 AVPlayer(包含在AVFoundation框架内)与 AVAudioPlayer 有点类似,但是 AVPlayer 的功能更加强大,它可以用来播放音频也可以用来播放视频。而且在播放音频方面 AVPlayer 可以直接播放网络音频。
2> 视频播放实现步骤
- 步骤一:导入支持视频播放的框架AVFoundation.framework
引入头文件代码
#import <AVFoundation/AVFoundation.h>
NSString *playString = @"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4";
// 播放地址
NSURL *playURL = [NSURL URLWithString:playString];
- 步骤三:根据播放的 URL 创建 AVPlayerItem 对象
AVPlayerItem 可以获取视频的信息,当前播放时间,总时间等
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:playURL];
AVPlayerItem 的重要属性
状态 status
AVPlayerStatusUnknown,(代表视频播放出现了未知的问题)
AVPlayerStatusReadyToPlay,(代表视频可以播放,可以调用 play方法)
AVPlayerStatusFailed(代表视频无法进行播放了)
loadedTimeRange:代表已经缓存的进度,监听此属性可以在 UI 中更新缓存进度,也是很有用的一个属性
- 步骤四:根据 AVPlayerItem 初始化 AVPlayer 对象
@interface ViewController ()
@property(nonatomic, strong)AVPlayer *player;
@end
self.player = [[AVPlayer alloc] initWithPlayerItem:item];
- 步骤五:把 AVPlayerLayer 添加到需要播放页面的 Layer 层
// 设置播放页面
AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:_player];
// 设置播放页面的大小
layer.frame = CGRectMake(0, 100, [UIScreen mainScreen].bounds.size.width, 300);
// 设置背景颜色
layer.backgroundColor = [UIColor cyanColor].CGColor;
// 设置播放窗口和当前视图之间的比例显示内容
layer.videoGravity = AVLayerVideoGravityResizeAspect;
// 添加播放视图到view上
[self.view.layer addSublayer:layer];
// 播放
[self.player play];
[self.player seekToTime:CMTimeMakeWithSeconds(progress,
//设置每秒钟多少帧
self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
}];
// 设置音量
self.player.volume = 1.0f;
// 当前播放时间
self.player.currentTime
//当播放完成时,可以注册通知,根据需求,做出不同的响应
AVPlayerItemDidPlayToEndTimeNotification
可以通过设置观察者来完成添加播放完成通知
-(void)addNotification{
//给AVPlayerItem添加播放完成通知
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:)name:AVPlayerItemDidPlayToEndTimeNotification object:self.player.currentItem];
}
-(void)playbackFinished:(NSNotification *)notification{
NSLog(@"视频播放完成.");
}
通过以上的六个步骤已经可以实现视频在 iOS 客户端的播放;
AVPlayerltem 资源管理对象,作用是:切换视频播放,使用时切换不同的 Item 即可. 而非创建新的 AVPlayer.
AVPlayerItem 的一些重要属性可以使我们定制视频的开发
实例代码:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *playString = @"http://static.tripbe.com/videofiles/20121214/9533522808.f4v.mp4";
NSURL *url = [NSURL URLWithString:playString];
// 本地视频
// NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"1457622279563.mp4" ofType:nil]];
// 设置播放的项目
AVPlayerItem *item = [[AVPlayerItem alloc] initWi