iOS实现播放远程网络音乐的核心技术点总结

2020-01-18 17:23:06王振洲

(1)开启后台模式

target ->capabilities-> Background modes ->打开开关 ->勾选第一个选项ios音乐播放器开发,ios,音乐播放器代码,ios网络音乐播放器

(2)程序启动时设置音频会话


  //一般在方法:application: didFinishLaunchingWithOptions:设置
  //获取音频会话
  AVAudioSession *session = [AVAudioSession sharedInstance];
  //设置类型是播放。
  [session setCategory:AVAudioSessionCategoryPlayback error:nil];
  //激活音频会话。
  [session setActive:YES error:nil];

以上两步设置无误,程序进入后台模式,便可以进行音乐播放

10、如何设置音乐锁频信息

我们看百度音乐锁频时,也依然能在屏幕上展示歌曲的信息,以及切换歌曲等。下面看看这个功能是如何实现的:


//音乐锁屏信息展示
- (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;
  }
}