-(AVPlayer *)player
{
if (_player == nil) {
// AVPlayerItem是一个包装音乐资源的类,初始化时可以传入一个音乐的url
AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:@"http://xxxxxxxx"]];
//通过AVPlayerItem初始化player
_player = [[AVPlayer alloc] initWithPlayerItem:item];
}
return _player;
}
//开始播放 [self.player play]; //停止播放 [self.player pause];
//创建需要播放的AVPlayerItem AVPlayerItem *item = [[AVPlayerItem alloc] initWithURL:[NSURL URLWithString:model.url]]; //替换当前音乐资源 [self.player replaceCurrentItemWithPlayerItem:item];
[self.player.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
typedef NS_ENUM(NSInteger, AVPlayerItemStatus) {
AVPlayerItemStatusUnknown,//未知状态
AVPlayerItemStatusReadyToPlay,//准备播放
AVPlayerItemStatusFailed//加载失败
};
//观察者回调
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
//注意这里查看的是self.player.status属性
if ([keyPath isEqualToString:@"status"]) {
switch (self.player.status) {
case AVPlayerStatusUnknown:
{
NSLog(@"未知转态");
}
break;
case AVPlayerStatusReadyToPlay:
{
NSLog(@"准备播放");
}
break;
case AVPlayerStatusFailed:
{
NSLog(@"加载失败");
}
break;
default:
break;
}
}
}
//移除观察者 [self.player.currentItem removeObserver:self forKeyPath:@"status"];
//KVO监听音乐缓冲状态 [self.player.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
NSArray * timeRanges = self.player.currentItem.loadedTimeRanges;
//本次缓冲的时间范围
CMTimeRange timeRange = [timeRanges.firstObject CMTimeRangeValue];
//缓冲总长度
NSTimeInterval totalLoadTime = CMTimeGetSeconds(timeRange.start) + CMTimeGetSeconds(timeRange.duration);
//音乐的总时间
NSTimeInterval duration = CMTimeGetSeconds(self.player.currentItem.duration);
//计算缓冲百分比例
NSTimeInterval scale = totalLoadTime/duration;
//更新缓冲进度条
self.loadTimeProgress.progress = scale;
}
}
typedef struct
{
CMTime start;
CMTime duration;
} CMTimeRange;
[self.player.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
/** 监听音乐播放进度 @param interval 监听的时间间隔,用来设置多长时间回调一次 @param queue 队列,一般传主队列 @param block 回调的block,会把当前的播放时间传递过来 @return 监听的对象 */ - (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(nullable dispatch_queue_t)queue usingBlock:(void (^)(CMTime time))block;
__weak typeof(self) weakSelf = self;
self.timeObserver = [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
//当前播放的时间
float current = CMTimeGetSeconds(time);
//总时间
float total = CMTimeGetSeconds(item.duration);
if (current) {
float progress = current / total;
//更新播放进度条
weakSelf.playSlider.value = progress;
weakSelf.currentTime.text = [weakSelf timeFormatted:current];
}
}];
typedef struct CMTimeValue value; CMTimeScale timescale; CMTimeFlags flags; CMTimeEpoch epoch; } CMTime;
Float64 CMTimeGetSeconds(CMTime time)
if (self.timeObserver) {
[self.player removeTimeObserver:self.timeObserver];
self.timeObserver = nil;
}
/**
定位播放时间
@param time 指定的播放时间
*/
- (void)seekToTime:(CMTime)time;
具体使用如下:
//移动滑块调整播放进度
- (IBAction)playSliderValueChange:(UISlider *)sender
{
//根据值计算时间
float time = sender.value * CMTimeGetSeconds(self.player.currentItem.duration);
//跳转到当前指定时间
[self.player seekToTime:CMTimeMake(time, 1)];
}
//给AVPlayerItem添加播放完成通知 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
//一般在方法:application: didFinishLaunchingWithOptions:设置 //获取音频会话 AVAudioSession *session = [AVAudioSession sharedInstance]; //设置类型是播放。 [session setCategory:AVAudioSessionCategoryPlayback error:nil]; //激活音频会话。 [session setActive:YES error:nil];
//音乐锁屏信息展示
- (void)setupLockScreenInfo
{
// 1.获取锁屏中心
MPNowPlayingInfoCenter *playingInfoCenter = [MPNowPlayingInfoCenter defaultCenter];
//初始化一个存放音乐信息的字典
NSMutableDictionary *playingInfoDict = [NSMutableDictionary dictionary];
// 2、设置歌曲名
if (self.currentModel.name) {
[playingInfoDict setObject:self.currentModel.name forKey:MPMediaItemPropertyAlbumTitle];
}
// 设置歌手名
if (self.currentModel.artist) {
[playingInfoDict setObject:self.currentModel.artist forKey:MPMediaItemPropertyArtist];
}
// 3设置封面的图片
UIImage *image = [self getMusicImageWithMusicId:self.currentModel];
if (image) {
MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
[playingInfoDict setObject:artwork forKey:MPMediaItemPropertyArtwork];
}
// 4设置歌曲的总时长
[playingInfoDict setObject:self.currentModel.detailDuration forKey:MPMediaItemPropertyPlaybackDuration];
//音乐信息赋值给获取锁屏中心的nowPlayingInfo属性
playingInfoCenter.nowPlayingInfo = playingInfoDict;
// 5.开启远程交互,只有开启这个才能进行远程操控
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
//监听远程交互方法
- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
switch (event.subtype) {
//播放
case UIEventSubtypeRemoteControlPlay:{
[self.player play];
}
break;
//停止
case UIEventSubtypeRemoteControlPause:{
[self.player pause];
}
break;
//下一首
case UIEventSubtypeRemoteControlNextTrack:
[self nextBtnAction:nil];
break;
//上一首
case UIEventSubtypeRemoteControlPreviousTrack:
[self lastBtnAction:nil];
break;
default:
break;
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有