天天看點

iOS開發之網絡音樂播放器(SC音樂)(二)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所示:

iOS開發之網絡音樂播放器(SC音樂)(二)iOS開發之網絡音樂播放器(SC音樂)(二)

圖1

iOS開發之網絡音樂播放器(SC音樂)(二)iOS開發之網絡音樂播放器(SC音樂)(二)

圖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哦!

githut位址: https://github.com/Mozartisnotmyname/SCMusic.git