iOS 音乐播放器之锁屏歌词+歌词解析+锁屏效果

功能描述:锁屏歌曲信息、控制台远程控制音乐播放:暂停/播放、上一首/下一首、快进/快退、锁屏状态下列表菜单弹框和拖拽控制台的进度条调节进度(结合了QQ音乐和网易云音乐在锁屏状态下的效果)、歌词解析并随音乐滚动显示。

总效果预览图.gif

第一部分:锁屏效果包括:锁屏歌曲信息和远程控制音乐播放

① 锁屏歌曲信息显示

iOS11以下锁屏信息预览
//展示锁屏歌曲信息:图片、歌词、进度、歌曲名、演唱者、专辑、(歌词是绘制在图片上的)
- (void)showLockScreenTotaltime:(float)totalTime andCurrentTime:(float)currentTime andLyricsPoster:(BOOL)isShow{

    NSMutableDictionary * songDict = [[NSMutableDictionary alloc] init];
    //设置歌曲题目
    [songDict setObject:@"多幸运" forKey:MPMediaItemPropertyTitle];
    //设置歌手名
    [songDict setObject:@"韩安旭" forKey:MPMediaItemPropertyArtist];
    //设置专辑名
    [songDict setObject:@"专辑名" forKey:MPMediaItemPropertyAlbumTitle];
    //设置歌曲时长
    [songDict setObject:[NSNumber numberWithDouble:totalTime]  forKey:MPMediaItemPropertyPlaybackDuration];
    //设置已经播放时长
    [songDict setObject:[NSNumber numberWithDouble:currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];

    UIImage * lrcImage = [UIImage imageNamed:@"backgroundImage5.jpg"];
    if (isShow) {

        //制作带歌词的海报
        if (!_lrcImageView) {
            _lrcImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 480,800)];
        }
        if (!_lockScreenTableView) {
            _lockScreenTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 800 - 44 * 7 + 20, 480, 44 * 3) style:UITableViewStyleGrouped];
            _lockScreenTableView.dataSource = self;
            _lockScreenTableView.delegate = self;
            _lockScreenTableView.separatorStyle = NO;
            _lockScreenTableView.backgroundColor = [UIColor clearColor];
            [_lockScreenTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cellID"];
        }
        //主要为了把歌词绘制到图片上,已达到更新歌词的目的
        [_lrcImageView addSubview:self.lockScreenTableView];
        _lrcImageView.image = lrcImage;
        _lrcImageView.backgroundColor = [UIColor blackColor];

        //获取添加了歌词数据的海报图片
        UIGraphicsBeginImageContextWithOptions(_lrcImageView.frame.size, NO, 0.0);
        CGContextRef context = UIGraphicsGetCurrentContext();
        [_lrcImageView.layer renderInContext:context];
        lrcImage = UIGraphicsGetImageFromCurrentImageContext();
        _lastImage = lrcImage;
        UIGraphicsEndImageContext();

    }else{
        if (_lastImage) {
            lrcImage = _lastImage;
        }
    }
    //设置显示的海报图片
    [songDict setObject:[[MPMediaItemArtwork alloc] initWithImage:lrcImage]
                 forKey:MPMediaItemPropertyArtwork];
   //加入正在播放媒体的信息中心
    [[MPNowPlayingInfoCenter defaultCenter] setNowPlayingInfo:songDict];

}

② 远程控制音乐播放

左侧列表菜单弹出框.PNG

在此之前需先满足后台播放音乐的条件:

//后台播放音频设置,需要在Capabilities->Background Modes中勾选Audio,Airplay,and Picture in Picture ,如下图1、2
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
1.png
2.png
  • 在iOS7.1之前, App如果需要在锁屏界面开启和监控远程控制事件,可以通过重写- (void)remoteControlReceivedWithEvent:(UIEvent *)event这个方法来捕获远程控制事件,并根据event.subtype来判别指令意图并作出反应。具体用法如下:
//在具体的控制器或其它类中捕获处理远程控制事件,当远程控制事件发生时触发该方法, 该方法属于UIResponder类,iOS 7.1 之前经常用
- (void)remoteControlReceivedWithEvent:(UIEvent *)event{
    NSLog(@"%ld",event.type);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"songRemoteControlNotification" object:self userInfo:@{@"eventSubtype":@(event.subtype)}];
}

 /* iOS 7.1之前*/
     //让App开始接收远程控制事件, 该方法属于UIApplication类
     [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
     //结束远程控制,需要的时候关闭
     //     [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
     //处理控制台的暂停/播放、上/下一首事件
     [[NSNotificationCenter defaultCenter] addObserverForName:@"songRemoteControlNotification" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *notification) {

     NSInteger  eventSubtype = [notification.userInfo[@"eventSubtype"] integerValue];
     switch (eventSubtype) {
     case UIEventSubtypeRemoteControlNextTrack:
     NSLog(@"下一首");
     break;
     case UIEventSubtypeRemoteControlPreviousTrack:
     NSLog(@"上一首");
     break;
     case  UIEventSubtypeRemoteControlPause:
     [self.player pause];
     break;
     case  UIEventSubtypeRemoteControlPlay:
     [self.player play];
     break;
     //耳机上的播放暂停
     case  UIEventSubtypeRemoteControlTogglePlayPause:
     NSLog(@"播放或暂停");
     break;
     //后退
     case UIEventSubtypeRemoteControlBeginSeekingBackward:
     break;
     case UIEventSubtypeRemoteControlEndSeekingBackward:
     NSLog(@"后退");
     break;
     //快进
     case UIEventSubtypeRemoteControlBeginSeekingForward:
     break;
     case UIEventSubtypeRemoteControlEndSeekingForward:
     NSLog(@"前进");
     break;
     default:
     break;
     }

     }];
  • 在iOS7.1之后,出现了MPRemoteCommandCenter、MPRemoteCommand 及其相关的一些类 ,锁屏界面开启和监控远程控制事件就更方便了,而且还扩展了一些新功能:网易云音乐的列表菜单弹框功能和QQ音乐的拖拽控制台的进度条调节进度功能等等…..
    官方文档:https://developer.apple.com/documentation/mediaplayer/mpremotecommandcenter
//锁屏界面开启和监控远程控制事件
- (void)createRemoteCommandCenter{
    /**/
    //远程控制命令中心 iOS 7.1 之后  详情看官方文档:https://developer.apple.com/documentation/mediaplayer/mpremotecommandcenter

    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];

    //   MPFeedbackCommand对象反映了当前App所播放的反馈状态. MPRemoteCommandCenter对象提供feedback对象用于对媒体文件进行喜欢, 不喜欢, 标记的操作. 效果类似于网易云音乐锁屏时的效果

    //添加喜欢按钮
    MPFeedbackCommand *likeCommand = commandCenter.likeCommand;
    likeCommand.enabled = YES;
    likeCommand.localizedTitle = @"喜欢";
    [likeCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"喜欢");
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    //添加不喜欢按钮,假装是“上一首”
    MPFeedbackCommand *dislikeCommand = commandCenter.dislikeCommand;
    dislikeCommand.enabled = YES;
    dislikeCommand.localizedTitle = @"上一首";
    [dislikeCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"上一首");
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    //标记
    MPFeedbackCommand *bookmarkCommand = commandCenter.bookmarkCommand;
    bookmarkCommand.enabled = YES;
    bookmarkCommand.localizedTitle = @"标记";
    [bookmarkCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"标记");
        return MPRemoteCommandHandlerStatusSuccess;
    }];

//    commandCenter.togglePlayPauseCommand 耳机线控的暂停/播放

    [commandCenter.pauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [self.player pause];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    [commandCenter.playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [self.player play];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    //    [commandCenter.previousTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
    //        NSLog(@"上一首");
    //        return MPRemoteCommandHandlerStatusSuccess;
    //    }];

    [commandCenter.nextTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"下一首");
        return MPRemoteCommandHandlerStatusSuccess;
    }];

    //快进
    //    MPSkipIntervalCommand *skipBackwardIntervalCommand = commandCenter.skipForwardCommand;
    //    skipBackwardIntervalCommand.preferredIntervals = @[@(54)];
    //    skipBackwardIntervalCommand.enabled = YES;
    //    [skipBackwardIntervalCommand addTarget:self action:@selector(skipBackwardEvent:)];

    //在控制台拖动进度条调节进度(仿QQ音乐的效果)
    [commandCenter.changePlaybackPositionCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        CMTime totlaTime = self.player.currentItem.duration;
        MPChangePlaybackPositionCommandEvent * playbackPositionEvent = (MPChangePlaybackPositionCommandEvent *)event;
        [self.player seekToTime:CMTimeMake(totlaTime.value*playbackPositionEvent.positionTime/CMTimeGetSeconds(totlaTime), totlaTime.timescale) completionHandler:^(BOOL finished) {
        }];
        return MPRemoteCommandHandlerStatusSuccess;
    }];


}

-(void)skipBackwardEvent: (MPSkipIntervalCommandEvent *)skipEvent
{
    NSLog(@"快进了 %f秒", skipEvent.interval);
}

第二部分:歌词解析

歌词样式.png
  • 根据上图的歌词样式,思路就是:先根据换行符“\n“分割字符串,获得包含每一行歌词字符串的数组,然后解析每一行歌词字符,获得时间点和对应的歌词,再用创建的歌词对象wslLrcEach来存储时间点和歌词,最后得到一个存储wslLrcEach对象的数组。
//每句歌词对象 
@interface wslLrcEach : NSObject 
@property(nonatomic, assign) NSUInteger time ; 
@property(nonatomic, copy) NSString * lrc ; 
@end

接下来就是要让歌词随歌曲的进度来滚动显示,主要代码如下:

self.tableView  显示歌词的
    currentTime  当前播放时间点
    self.currentRow  当前时间点歌词的位置

     //歌词滚动显示
        for ( int i = (int)(self.lrcArray.count - 1); i >= 0 ;i--) {
            wslLrcEach * lrc = self.lrcArray[i];
            if (lrc.time < currentTime) {
                self.currentRow = i;
                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow: self.currentRow inSection:0] atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
                [self.tableView reloadData];
                break;
            }
        }

传送门~

iOS11锁屏界面.PNG
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,688评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,559评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,749评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,581评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,741评论 3 271
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,684评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,122评论 2 292
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,847评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,441评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,939评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,333评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,783评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,275评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,830评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,444评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,553评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,618评论 2 249

推荐阅读更多精彩内容

  • LyricsAnalysis 功能描述:锁屏歌曲信息、控制台远程控制音乐播放:暂停/播放、上一首/下一首、快进/快...
    且行且珍惜_iOS阅读 21,346评论 69 139
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    X先生_未知数的X阅读 15,931评论 3 118
  • 三年前,随着大宝的到来,我成为了母亲,初为人母的喜悦随着宝宝日常吃喝拉撒而趋于平淡。每天对着宝宝最关心的问题就是奶...
    奕林南阅读 137评论 0 0
  • 春来花渐茂, 暴雨落红凋。 风吹翩翩舞, 暗送幽幽香。 艳极为君绽, 不为他人芳。 试问无情雨, 心冷似铁石。 赠...
    探索书海阅读 81评论 0 0
  • 从来没有过这样的低声下气,我应该是有受虐倾向。
    山丘在哪里阅读 137评论 0 0