前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >iOS后台音频播放及锁屏歌词

iOS后台音频播放及锁屏歌词

作者头像
且行且珍惜_iOS
发布2018-05-22 16:56:33
1.7K0
发布2018-05-22 16:56:33
举报
文章被收录于专栏:iOS开发攻城狮的集散地

1.PNG

2.PNG

主要代码如下:

代码语言:javascript
复制
//后台播放音频设置,需要在Capabilities->Background Modes中勾选Audio,Airplay,and Picture in Picture
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];

//开始接受远程控制
     [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
     //结束远程控制,需要的时候关闭
     //     [[UIApplication sharedApplication] endReceivingRemoteControlEvents];

//处理后台传递给我们的信息,用于音乐,在AppDelegate.m中重写
    - (void)remoteControlReceivedWithEvent:(UIEvent *)event{
    //处理后台传递给我们的控制信息,用于音乐
    if (event.type == UIEventTypeRemoteControl) {
     
        NSLog(@"%ld",event.subtype);
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"songControlNotification" object:self userInfo:@{@"subtype":@(event.subtype)}];
        
        /*
         
         subtype中的枚举便是点击这些控制键后传递给我们的消息,我们可以根据这些消息在app内做逻辑处理。枚举如下,其中只有100之后的在音频控制中对我们有效:
         
         typedef NS_ENUM(NSInteger, UIEventSubtype) {
         
            // available in iPhone OS 3.0
            UIEventSubtypeNone                              = 0,
            // for UIEventTypeMotion, available in iPhone OS 3.0
            UIEventSubtypeMotionShake                       = 1,
            //这之后的是我们需要关注的枚举信息
            // for UIEventTypeRemoteControl, available in iOS 4.0
            //点击播放按钮或者耳机线控中间那个按钮
            UIEventSubtypeRemoteControlPlay                 = 100,
            //点击暂停按钮
            UIEventSubtypeRemoteControlPause                = 101,
            //点击停止按钮
            UIEventSubtypeRemoteControlStop                 = 102,
            //点击播放与暂停开关按钮(iphone抽屉中使用这个)
            UIEventSubtypeRemoteControlTogglePlayPause      = 103,
            //点击下一曲按钮或者耳机中间按钮两下
            UIEventSubtypeRemoteControlNextTrack            = 104,
            //点击上一曲按钮或者耳机中间按钮三下
            UIEventSubtypeRemoteControlPreviousTrack        = 105,
            //快退开始 点击耳机中间按钮三下不放开
            UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
            //快退结束 耳机快退控制松开后
            UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
            //开始快进 耳机中间按钮两下不放开
            UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
            //快进结束 耳机快进操作松开后
            UIEventSubtypeRemoteControlEndSeekingForward    = 109,
        };
     */
        
        }
    }


    //监听锁屏状态 lock=1则为锁屏状态
        uint64_t locked;
        __block int token = 0;
       notify_register_dispatch("com.apple.springboard.lockstate",&token,dispatch_get_main_queue(),^(int t){
        });
        notify_get_state(token, &locked);
        
        //监听屏幕点亮状态 screenLight=1则为变暗关闭状态
        uint64_t screenLight;
        __block int lightToken = 0;
    notify_register_dispatch("com.apple.springboard.hasBlankedScreen",&lightToken,dispatch_get_main_queue(),^(int t){
        });
        notify_get_state(lightToken, &screenLight);
        
       // NSLog(@"screenLight=%llu locked=%llu",screenLight,locked);
        if (screenLight == 1|| locked == 0) {
            return;
        }
        //锁屏信息
            [self showLockScreenTotaltime:totalSeconds andCurrentTime:playSeconds];




    //锁屏控制音乐播放事件的通知
    - (void)addNotification{
    
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(songPlayControl:) name:@"songControlNotification" object:nil];
    
    }
    - (void)songPlayControl:(NSNotification *)noti{  
       NSNumber* subtype = noti.userInfo[@"subtype"];
    int type = [subtype intValue];
    switch (type) {
          case UIEventSubtypeRemoteControlNextTrack:
            [self nextSongBtnClick];
            break;
          case UIEventSubtypeRemoteControlPreviousTrack:
            [self previousSongBtnClick];
            break;
          case  UIEventSubtypeRemoteControlPause:
            [self playBtnClick:_playBtn];
            break;
            case  UIEventSubtypeRemoteControlPlay:
            [self playBtnClick:_playBtn];
            break;
        default:
            break;
        }
       }






    #pragma mark --- 锁屏歌曲信息
    - (void)showLockScreenTotaltime:(float)totalTime andCurrentTime:(float)currentTime{
    
    NSMutableDictionary * songDict = [[NSMutableDictionary alloc] init];
    SongModel * songModel = self.songArray[_playIndex];
    //设置歌曲题目
    [songDict setObject:songModel.songName forKey:MPMediaItemPropertyTitle];
    //设置歌手名
    [songDict setObject:songModel.singerName forKey:MPMediaItemPropertyArtist];
    //设置专辑名
    [songDict setObject:songModel.songName forKey:MPMediaItemPropertyAlbumTitle];
    //设置歌曲时长
    [songDict setObject:[NSNumber numberWithDouble:totalTime] forKey:MPMediaItemPropertyPlaybackDuration];
    //设置已经播放时长
    [songDict setObject:[NSNumber numberWithDouble:currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    
    if (!_lrcImageView) {
        _lrcImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width - 100,self.view.frame.size.width - 100 + 50)];
        
    }
    [_lrcImageView addSubview:self.lockScreenTableView];
     _lrcImageView.image = _songImage.image;
    
    //获取添加了歌词数据的背景图

    UIGraphicsBeginImageContextWithOptions(_lrcImageView.frame.size, NO, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [_lrcImageView.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    //设置显示的图片
    [songDict setObject:[[MPMediaItemArtwork alloc] initWithImage:img]
             forKey:MPMediaItemPropertyArtwork];
    
    //更新字典
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songDict];
    
    }

demo和最新相关知识可以去我的这篇文章里查看: iOS 音乐播放器之锁屏效果+歌词解析

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2016.05.13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档