竹影音乐——iOS实现网络音乐播放器

AVPlayer

AVPlayer播放器存在于AVFoundation中, 能够播放网络和本地视频/音频, 和MediaPlayer.framework框架下的两个播放器不同, 并没有默认的UI界面,是一个高度自定义的播放器。与AVAudioPlayer相比,,AVPlayer可以实现流媒体播放,而AVAudioPlayer只能缓存完再播放。

竹影音乐——iOS实现网络音乐播放器_第1张图片
0.PNG

AVPlayer实现

AVPlayer通过asset来初始化player,当然也可以直接用URL初始化

  NSURL *musicURL = [self.tracksVM playURLForRow:_indexPathRow];
  AVPlayerItem *currentPlayerItem = [AVPlayerItem playerItemWithURL:musicURL];
  _player = [[AVPlayer alloc] initWithPlayerItem:currentPlayerItem];

如果要使用视频播放,需要再添加AVPlayerLayer

 //设置播放页面
 AVPlayerLayer *layer = [AVPlayerLayer playerLayerWithPlayer:_player];
 layer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 300);
 layer.backgroundColor = [UIColor cyanColor].CGColor;
 //设置播放窗口和当前视图之间的比例显示内容
 layer.videoGravity = AVLayerVideoGravityResizeAspect;
 //添加到self.view
 [self.view.layer addSublayer:layer];
1.gif

AVPlayerLayer常用操作

  [self.player play];//播放
  [self.player pause];//暂停

  [self.player seekToTime:CMTimeMake(0, 1)];//改变进度
  [self.player.currentItem currentTime]//当前时间
  [self.player.currentItem duration]//总时间
  self.player.volume = 1.0f;//设置音量

当切换上下首时使用replaceCurrentItemWithPlayerItem方法,可以切换item,但是发现切换时会造成卡顿,后来使用initWithPlayerItem替代解决

  [self.player replaceCurrentItemWithPlayerItem:_currentPlayerItem];//切换item
2.gif

监听AVPlayer

通过addPeriodicTimeObserverForInterval:监听进度变化,interval参数为响应的间隔时间,这里设为每秒都响应,queue是队列,传NULL代表在主线程执行。并且可以更新UI,比如进度条的当前时间与音频总长度。

- (id)addPeriodicTimeObserverForInterval:(CMTime)interval queue:(dispatch_queue_t)queue usingBlock:(void (^)

监听AVPlayer是否播放完成,完成后按照当前状态执行操作

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:[self.player currentItem]];
-(void)playbackFinished:(NSNotification *)notification{
    
    if (_cycle == theSong) {
        [self playAgain];
    }else if(_cycle == nextSong){
        [self playNextMusic];
    }else if(_cycle == isRandom){
        [self randomMusic];
    }
    NSLog(@"开始下一首");
    [self.delegate changeMusic];
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    userInfo[@"coverURL"] = [self.tracksVM coverURLForRow:_indexPathRow];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeCoverURL" object:nil userInfo:userInfo];
}

设置后台播放,与锁屏时展示歌曲信息控制播放

  // 支持后台播放
  [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
  // 激活
  [[AVAudioSession sharedInstance] setActive:YES error:nil];
  // 开始监控
  [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    // 播放信息中心
    MPNowPlayingInfoCenter *center = [MPNowPlayingInfoCenter defaultCenter];
    
    // 初始化播放信息
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    // 专辑名称
    info[MPMediaItemPropertyAlbumTitle] = [self playMusicName];
    // 歌手
    info[MPMediaItemPropertyArtist] = [self playSinger];
    // 歌曲名称
    info[MPMediaItemPropertyTitle] = [self playMusicTitle];
    // 设置图片
    info[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:[self playCoverImage]];
    // 设置持续时间(歌曲的总时间)
    [info setObject:[NSNumber numberWithFloat:CMTimeGetSeconds([self.player.currentItem duration])] forKey:MPMediaItemPropertyPlaybackDuration];
    // 设置当前播放进度
    [info setObject:[NSNumber numberWithFloat:CMTimeGetSeconds([self.player.currentItem currentTime])] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    
    // 切换播放信息
    center.nowPlayingInfo = info;
3.gif

远程控制事件 Remote Control Event可以在不打开app时,控制音乐播放器播放

  // 成为第一响应者(必备条件)
  [self becomeFirstResponder];

#pragma mark - 远程控制事件监听
- (BOOL)canBecomeFirstResponder{
    return YES;
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event{
    
    //    event.type; // 事件类型
    //    event.subtype; // 事件的子类型
    //    UIEventSubtypeRemoteControlPlay                 = 100,
    //    UIEventSubtypeRemoteControlPause                = 101,
    //    UIEventSubtypeRemoteControlStop                 = 102,
    //    UIEventSubtypeRemoteControlTogglePlayPause      = 103,
    //    UIEventSubtypeRemoteControlNextTrack            = 104,
    //    UIEventSubtypeRemoteControlPreviousTrack        = 105,
    //    UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
    //    UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
    //    UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
    //    UIEventSubtypeRemoteControlEndSeekingForward    = 109,
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:
            [[FYPlayManager sharedInstance] pauseMusic];
            break;
            
        case UIEventSubtypeRemoteControlNextTrack:
            [[FYPlayManager sharedInstance] nextMusic];
            break;
            
        case UIEventSubtypeRemoteControlPreviousTrack:
            [[FYPlayManager sharedInstance] previousMusic];
            
        default:
            break;
    }
}

AVPlayerLayer是流媒体播放,如果要实现边下边缓存,缓存完成下载好文件的话,需要自定义scheme来创建avplayer,在资源的 URL 不能被系统识别时会自定义视频加载,从而使用AVAssetResourceLoaderDelegate

源码链接:GitHub地址 不给个star吗(´・ω・)

你可能感兴趣的:(竹影音乐——iOS实现网络音乐播放器)