iOS开发之网络音乐播放器(SC音乐)(二)

iOS开发之网络音乐播放器(SC音乐)(二)



前言



iOS开发之网络音乐播放器(SC音乐)(一)已经介绍完播放控制、音乐数据获取解析、歌词显示等。本文在上文的基础上介绍锁屏播放设置,后台播放设置,手势操作等。



正题


一、后台播放设置


点击工程Target-->Info或者打开Info.plist文件,在"Infomation Property List"中添加"Required background modes",将"Required background modes"下拉项目Item0中的Value设置为"App plays audio or streams audio/video using AirPlay",点击Target-->Capabilities,勾选"Audio, AirPlay and Picture in Picture"。如图1和图2所示:

图1




图2

然后在AppDelegate.m文件的方法- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

return YES;
} 添加以下代码:

//后台播放音频设置,需要在Capabilities->Background Modes中勾选Audio,Airplay,and Picture in Picture
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
这样就可以实现后台播放了。


二、锁屏播放设置

在AppDelegate.m文件的方法- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

return YES;
}添加以下代码:

 // 设置接受远程控制
 [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];


在ViewController.h中添加头文件:

#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>


在ViewController.m文件添加方法:

#pragma mark - 锁屏界面开启和监控远程控制事件
//锁屏界面开启和监控远程控制事件
- (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(@"下一首");
        [self nextButtonAction:nil];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    //标记
    MPFeedbackCommand *bookmarkCommand = commandCenter.bookmarkCommand;
    bookmarkCommand.enabled = YES;
    bookmarkCommand.localizedTitle = @"标记";
    [bookmarkCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"标记");
        
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    // 远程控制播放
    [commandCenter.pauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [musicPlayer.play pause];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    // 远程控制暂停
    [commandCenter.playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [musicPlayer.play play];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    // 远程控制上一曲
    [commandCenter.previousTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"上一曲");
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    // 远程控制下一曲
    [commandCenter.nextTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"下一曲");
        [self nextButtonAction:nil];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    
    //快进
    MPSkipIntervalCommand *skipBackwardIntervalCommand = commandCenter.skipForwardCommand;
    skipBackwardIntervalCommand.preferredIntervals = @[@(54)];
    skipBackwardIntervalCommand.enabled = YES;
    [skipBackwardIntervalCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        
        NSLog(@"你按了快进按键!");
        
        // 歌曲总时间
        CMTime duration = musicPlayer.play.currentItem.asset.duration;
        Float64 completeTime = CMTimeGetSeconds(duration);
        
        // 快进10秒
        _songSlider.value = _songSlider.value + 10 / completeTime;
        
        // 计算快进后当前播放时间
        Float64 currentTime = (Float64)(_songSlider.value) * completeTime;
        
        // 播放器定位到对应的位置
        CMTime targetTime = CMTimeMake((int64_t)(currentTime), 1);
        [musicPlayer.play seekToTime:targetTime];
        
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    //在控制台拖动进度条调节进度(仿QQ音乐的效果)
    [commandCenter.changePlaybackPositionCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        CMTime totlaTime = musicPlayer.play.currentItem.duration;
        MPChangePlaybackPositionCommandEvent * playbackPositionEvent = (MPChangePlaybackPositionCommandEvent *)event;
        [musicPlayer.play seekToTime:CMTimeMake(totlaTime.value*playbackPositionEvent.positionTime/CMTimeGetSeconds(totlaTime), totlaTime.timescale) completionHandler:^(BOOL finished) {
        }];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    
    
}

在ViewDidLoad方法中调用:
[self createRemoteCommandCenter];



#pragma mark - 锁屏播放设置
//展示锁屏歌曲信息:图片、歌词、进度、演唱者
- (void)showLockScreenTotaltime:(float)totalTime andCurrentTime:(float)currentTime andLyricsPoster:(BOOL)isShow{
    
    NSMutableDictionary * songDict = [[NSMutableDictionary alloc] init];
    //设置歌曲题目
    [songDict setObject:songInfo.title forKey:MPMediaItemPropertyTitle];
    //设置歌手名
    [songDict setObject:songInfo.author forKey:MPMediaItemPropertyArtist];
    //设置专辑名
    [songDict setObject:songInfo.album_title forKey:MPMediaItemPropertyAlbumTitle];
    //设置歌曲时长
    [songDict setObject:[NSNumber numberWithDouble:totalTime]  forKey:MPMediaItemPropertyPlaybackDuration];
    //设置已经播放时长
    [songDict setObject:[NSNumber numberWithDouble:currentTime] forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    
    UIImage * lrcImage = songInfo.pic_big;
    if (isShow) {
        
        //制作带歌词的海报
        if (!_lrcImageView) {
            _lrcImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 480,800)];
        }
        
        //主要为了把歌词绘制到图片上,已达到更新歌词的目的
        [_lrcImageView addSubview:_deliverView.midView.midLrcView.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];
    
}

在更新播放进度的方法中调用:
//展示锁屏歌曲信息,上面监听屏幕锁屏和点亮状态的目的是为了提高效率
[self showLockScreenTotaltime:totalTime andCurrentTime:currentTime andLyricsPoster:isShowLyricsPoster];

锁屏歌词实现原理是将锁屏歌词tableView加到锁屏专辑图片imageView中,合成新图片,歌词滚动的时候刷新tableView,然后就可以实现锁屏歌词滚动了。

三、手势操作

SC音乐用到了点击主页控制View进入DetailPlayControlView,下滑退出DetailPlayControlView的操作,所以要给主页控制View添加点击和下滑手势操作。

1). 点击操作

// 主页控制View
_playControllerView = [[UIView alloc] initWithFrame:CGRectMake(0, Screen_Height * 0.88, Screen_Width, Screen_Height * 0.12)];
_playControllerView.backgroundColor = UIColorFromRGB(0xff0000);
_playControllerView.userInteractionEnabled = YES;
UITapGestureRecognizer *tapGesturRecognizer=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
[_playControllerView addGestureRecognizer:tapGesturRecognizer];

#pragma mark - 主页控制View点击事件
-(void)tapAction:(id)tap
{
    NSLog(@"点击了tapView");
}


2). 下滑操作

// 向下滑动退出
UISwipeGestureRecognizer *recognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(responseGlide)];
[recognizer setDirection:(UISwipeGestureRecognizerDirectionDown)];
[self.deliverView  addGestureRecognizer:recognizer];

#pragma mark - 下滑退出detail控制界面
- (void)responseGlide {
 
    NSLog(@"下滑退出");

}

后续还会继续更新播放被外部中断怎么恢复播放功能,项目已经放到github,大家要是觉得这个项目对你有帮助,别忘了给颗Star哦!



没有更多推荐了,返回首页