AVPlayer播放

AVPlayer音頻播放器基本實現

#import <AVFoundation/AVFoundation.h>
@property (nonatomic, strong) AVPlayer *player;markdown

  • 播放
- (void)playWithURL:(NSURL *)url {    
    // 1. 資源的請求
    AVURLAsset *asset = [AVURLAsset assetWithURL:url];
    
    // 2. 資源的組織
    AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
    // 當資源的組織者, 告訴咱們資源準備好了以後, 咱們再播放
    // AVPlayerItemStatus status
    [item addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    // 3. 資源的播放
    self.player = [AVPlayer playerWithPlayerItem:item];
    
}

複製代碼
  • 暫停
- (void)pause {
    [self.player pause];
}
複製代碼
  • 繼續
- (void)resume {
    [self.player play];
}
複製代碼
  • 中止
- (void)stop {
    [self.player pause];
    self.player = nil;
}
複製代碼
  • 進度條拉動
- (void)seekWithProgress:(float)progress {

    if (progress < 0 || progress > 1) {
        return;
    }

    // 能夠指定時間節點去播放
    // 時間: CMTime : 影片時間
    // 影片時間 -> 秒
    // 秒 -> 影片時間
    
    // 1. 當前音頻資源的總時長
    CMTime totalTime = self.player.currentItem.duration;
    // 2. 當前音頻, 已經播放的時長
//    self.player.currentItem.currentTime
    
    NSTimeInterval totalSec = CMTimeGetSeconds(totalTime);
    NSTimeInterval playTimeSec = totalSec * progress;
    CMTime currentTime = CMTimeMake(playTimeSec, 1);
    
    [self.player seekToTime:currentTime completionHandler:^(BOOL finished) {
        if (finished) {
            NSLog(@"肯定加載這個時間點的音頻資源");
        }else {
            NSLog(@"取消加載這個時間點的音頻資源");
        }
    }];
    
    
}
複製代碼
  • 快進一段時間
- (void)seekWithTimeDiffer:(NSTimeInterval)timeDiffer {
    
    // 1. 當前音頻資源的總時長
    CMTime totalTime = self.player.currentItem.duration;
    NSTimeInterval totalTimeSec = CMTimeGetSeconds(totalTime);
    // 2. 當前音頻, 已經播放的時長
    CMTime playTime = self.player.currentItem.currentTime;
    NSTimeInterval playTimeSec = CMTimeGetSeconds(playTime);
    playTimeSec += timeDiffer;
    
    
    
    [self seekWithProgress:playTimeSec / totalTimeSec];
    
}
複製代碼
  • 倍數播放
- (void)setRate:(float)rate {
    
    [self.player setRate:rate];
    
}
複製代碼
  • 靜音
- (void)setMuted:(BOOL)muted {
    self.player.muted = muted;
}
複製代碼
  • 調節音量
- (void)setVolume:(float)volume {
    
    if (volume < 0 || volume > 1) {
        return;
    }
    if (volume > 0) {
        [self setMuted:NO];
    }
    
    self.player.volume = volume;
}
複製代碼
#pragma mark - KVO
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus status = [change[NSKeyValueChangeNewKey] integerValue];
        if (status == AVPlayerItemStatusReadyToPlay) {
            NSLog(@"資源準備好了, 這時候播放就沒有問題");
            [self.player play];
        }else {
            NSLog(@"狀態未知");
        }
    }
}
複製代碼
相關文章
相關標籤/搜索