iOS AVplayer 基本使用方法

时间:2022-02-26 05:17:33

*说明:利用AVPlayer可以制作视频播放器、音频播放器;使用AVPlayer播放过的格式有 .mp4  .m3u8   .mp3

1、创建播放器:

_player = [[AVPlayer alloc] initWithPlayerItem:[AVPlayerItem playerItemWithURL:[NSURL URLWithString:@""]]];

2、切换播放地址

    AVPlayerItem *item = [AVPlayerItem playerItemWithURL:mediaUrl];
[_player replaceCurrentItemWithPlayerItem:item];

3、跳转进度, 参数second秒

    CMTime changedTime = CMTimeMakeWithSeconds(second, 1);
[_player seekToTime:changedTime completionHandler:^(BOOL finished) {
}];

4、改变播放速率 0.5为正常速度的一半 默认rate是1 

    [_player setRate:0.5];

5、暂停/继续

    [_player pause];
[_player play];

6、播放时间(单位:秒)

    CGFloat currentPlayTime =_player.currentItem.currentTime.value/_player.currentItem.currentTime.timescale;

7、缓冲时间

    NSArray *loadedTimeRanges = [[_player currentItem] loadedTimeRanges];
CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];//获取缓冲区域
float startSeconds = CMTimeGetSeconds(timeRange.start);
float durationSeconds = CMTimeGetSeconds(timeRange.duration);
NSTimeInterval result = startSeconds + durationSeconds;//计算缓冲总进度