iOS使用AVPlayer播放音乐

最近在弄一个相关播放音频的项目,网上已经有很多相关avplayer的讲解,这里就不多说了。直接上代码



初始化

+ (instancetype)manager{

static AVPlayerManager * manager;

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

manager = [[AVPlayerManager alloc] init];

manager.player = [[AVPlayer alloc] init];

AVAudioSession *session = [AVAudioSession sharedInstance];

[session setActive:YES error:nil];

[session setCategory:AVAudioSessionCategoryPlayback error:nil];

});

return manager;

}

播放音频

- (void)updateAVPlayer{

if (isRemoveNot) {

[self removeObserverNotify];

isRemoveNot = NO;

}

MusicModel *model;

model = self.musicList[_index];

_playingModel = model;

playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:_playingModel.musicURL]];

[self.player replaceCurrentItemWithPlayerItem:playerItem];

[playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];

// 监听播放状态

@weakify(self);

@weakify(playerItem);

_playTimeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 20) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {

@strongify(self);

@strongify(playerItem);

float current = CMTimeGetSeconds(time);

float total = CMTimeGetSeconds(playerItem.duration);

if (current) {

self.progress = current;

self.totalProgress = total;

notify_refresh

}

}];

[[[NSNotificationCenter defaultCenter] rac_addObserverForName:AVPlayerItemDidPlayToEndTimeNotification object:nil] subscribeNext:^(NSNotification *notification) {

DebugLog(@"music play end!");

[self next];

[self pause];

}];

isRemoveNot = YES;

}

调整播放速率

//速率 rate 0.5~2.0 default 1

- (void)setPlayerSpeed:(float)rate{

[self.player setRate:rate];

}

快进快退秒速实现

//快进15秒

- (void)stepForward15Seconds{

[self.player.currentItem seekToTime:CMTimeMakeWithSeconds(self.player.currentItem.currentTime.value/self.player.currentItem.currentTime.timescale + 15, self.player.currentItem.currentTime.timescale) toleranceBefore:CMTimeMake(1, self.player.currentItem.currentTime.timescale) toleranceAfter:CMTimeMake(1, self.player.currentItem.currentTime.timescale)];

}

//快退15秒

- (void)stepReverse15Senconds{

[self.player.currentItem seekToTime:CMTimeMakeWithSeconds(self.player.currentItem.currentTime.value/self.player.currentItem.currentTime.timescale - 15, self.player.currentItem.currentTime.timescale)];

}

播放特定时间(拖动进度条)

- (void)setToTime:(CMTime)time{

[playerItem seekToTime:time];

}

附上demo代码,各位大神自己去研究吧~~核心代码

你可能感兴趣的:(iOS使用AVPlayer播放音乐)