美文网首页iOS ProcessiOS 实用iOS学习开发
学习之—后台、锁屏模式三部曲

学习之—后台、锁屏模式三部曲

作者: sydie | 来源:发表于2015-09-19 00:27 被阅读721次
  • 1.需要进入Capabilities将后台模式打开,根据需要选择后台模式。


    Snip20150910_1.png
  • 2.在AppDelegate中激活对应的后台模式。
 // 获取音频会话
    AVAudioSession *session = [AVAudioSession sharedInstance];
    // 设置后台模式
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    // 激活后台模式
    [session setActive:YES error:nil];
  • 3.设置锁屏界面的信息,接收远程事件。
#pragma mark - 设置锁屏信息
- (void)setUpLockScreenInfoWithPlayingMusic:(CXLMusic *)playingMusic
{
    //    1.获取锁屏信息
    MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];
    
    // 设置锁屏界面信息
        // 获取歌名、歌手名、歌手照片等信息
    NSMutableDictionary *playingInfo = [NSMutableDictionary dictionary];
    playingInfo[MPMediaItemPropertyAlbumTitle] = playingMusic.name;
    playingInfo[MPMediaItemPropertyAlbumArtist] = playingMusic.singer;
    playingInfo[MPMediaItemPropertyArtwork] = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:playingMusic.singerIcon]];
    playingInfo[MPMediaItemPropertyPlaybackDuration] = @(self.currentPlayer.duration);
  // 设置信息 
    infoCenter.nowPlayingInfo = playingInfo;
    
    // 接收远程事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:
            [self playOrPuase];
            break;
        case UIEventSubtypeRemoteControlNextTrack:
            [self nextMusicClick];
            break;
            case UIEventSubtypeRemoteControlPreviousTrack:
            [self preMusicClick];
            break;
            
        default:
            break;
    }
}
  • 注:这里接收远程事件是为了处理用户在锁屏模式时作出的操作。后台锁屏模式只能在真机测试,虚拟机无效。
Snip20150919_6.png

相关文章

网友评论

  • AlwaysBlue:setUpLockScreenInfoWithPlayingMusic 设置播放音乐信息在哪个地方调用呢
  • iOS_Xue:请问一下这种锁屏封面是不是只有音乐类的app才有啊?普通的app可以设置吗
  • JornyQi: 求demo,谢谢。。。1024399113@qq.com
  • df518cc365c1:还有一个问题,按照你的文章的做法,的确可以在后台播放音频。但是一旦当前音频播放结束,程序里监测到播放结束并要播放下一首音频就不可以了。
    sydie:是可以的啊
  • df518cc365c1:我觉得文章可以再严谨一点。比如并不一定要在 AppDelegate 中激活对应的后台模式,代码的其它地方也可以激活后台模式。
    sydie:不好意思,之前密码丢了就一直没来。其他地方能不能设置我还没有尝试过。
  • 87bd2ec3f227:学到了,请问楼主有相关的demo么
    8b415deb2960:同求 mikegod@foxmail.com
    87bd2ec3f227:@sydie 能发我邮箱么,非常感谢, zq4950411@163.com
    sydie:@羽弓 有一个音乐播放器的demo。

本文标题:学习之—后台、锁屏模式三部曲

本文链接:https://www.haomeiwen.com/subject/drwbcttx.html