AVPlayer: iOS的高级播放器
最编程
2024-08-13 14:39:48
...
AVPlayer 是 iOS 中比较常用的播放器,灵活性高,功能强大。
创建 player
AVAsset *asset = [AVAsset assetWithURL:[NSURL fileURLWithPath:outputString]];
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
_player = [AVPlayer playerWithPlayerItem:item];
设置预览图层
_playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
[self.view.layer addSublayer:_playerLayer];
_playerLayer.frame = self.view.bounds;
播放
[_player play];
循环播放
这里用Observer去监听播放器的时间,如果快播完了,就seek到0秒。
float duration = CMTimeGetSeconds(asset.duration);
__strong typeof(self) weakSelf = self;
[self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 30.0)
queue:dispatch_get_main_queue()
usingBlock:^(CMTime time) {
__strong typeof(weakSelf) strongSelf = weakSelf;
NSLog(@"%@__%@", @(duration), @(CMTimeGetSeconds(time)));
if (duration - CMTimeGetSeconds(time) <= 0.01) {
[strongSelf.player seekToTime:kCMTimeZero];
[strongSelf.player play];
}
}];
暂停
[_player pause];
seek
[_player seekToTime:kCMTimeZero];
[_player play];
倍速
可以在播放的时候改变。
_player.rate = 2;
这里介绍了一些常用的播放器操作,还有一些细节需要注意,比如前后台切换,音频路由等。
推荐阅读