iOS 開發項目之 QQ 音樂

版權聲明:本文爲博主原創文章,未經博主允許不得轉載。 https://blog.csdn.net/ab20514/article/details/50388221

一 框架搭建

  • 添加一個毛玻璃效果
- (void)setupBlurGlass
{
    // 1.創建UIToolbar
    UIToolbar *toolbar = [[UIToolbar alloc] init];
    toolbar.barStyle = UIBarStyleBlack;
    [self.albumView addSubview:toolbar];

    // 2.UIToolbar添加約束
    [toolbar mas_makeConstraints:^(MASConstraintMaker *make) {
        /*
        make.width.equalTo(self.albumView.mas_width);
        make.height.equalTo(self.albumView.mas_height);
        make.centerX.equalTo(self.albumView.mas_centerX);
        make.centerY.equalTo(self.albumView.mas_centerY);
         */
        make.edges.equalTo(self.albumView);
    }];
}
  • 設置狀態欄字體爲白色
- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}
  • 歌手圖片繪製成圓形
// 顏色抽成一個宏
#define GGColor(r,g,b) ([UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0])

- (void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];

    // 設置歌手圖片的圓角
    self.iconView.layer.cornerRadius = self.iconView.bounds.size.width * 0.5;
    self.iconView.layer.masksToBounds = YES;
    self.iconView.layer.borderWidth = 8;
    self.iconView.layer.borderColor = GGColor(40, 40, 40).CGColor;
}

二 播放音樂

  • 抽取工具類MusicTool,管理所有歌曲
static NSArray *_musics;
static GGMusic *_playingMusic;

+ (void)initialize
{
 // 使用MJExtension 框架
    _musics = [GGMusic objectArrayWithFilename:@"Musics.plist"];
    _playingMusic = _musics[0];
}

+ (NSArray *)musics
{
    return _musics;
}
// 獲取當前正在播放的歌曲
+ (GGMusic *)playingMusic
{
    return _playingMusic;
}
// 設置正在播放的歌曲
+ (void)setPlayingMusic:(GGMusic *)playingMusic
{
    _playingMusic = playingMusic;
}
  • 用工具類播放音樂
#pragma mark - 開始播放歌曲
- (void)startPlayingMusic
{
    // 1.取出當前播放的歌曲
    GGMusic *playingMusic = [GGMusicTool playingMusic];

    // 2.設置界面的基本展示
    self.albumView.image = [UIImage imageNamed:playingMusic.icon];
    self.iconView.image = [UIImage imageNamed:playingMusic.icon];
    self.songLabel.text = playingMusic.name;
    self.singerLabel.text = playingMusic.singer;

    // 3.開始播放歌曲
    AVAudioPlayer *player = [GGAudioTool playMusicWithMusicName:playingMusic.filename];
    self.currentTimeLabel.text = [NSString stringWithTime:player.currentTime]; // 當前時間
    self.totalTimeLabel.text = [NSString stringWithTime:player.duration];  // 總時間
    self.player = player;

    // 4.給iconView添加旋轉動畫
    [self addIconViewAnimation];

    // 5.添加定時器
    [self startProgressTimer];
}
  • 新建分類NSString+GGTimeToString,時間轉換拼接爲字符串
+ (NSString *)stringWithTime:(NSTimeInterval)time
{
    NSInteger min = time / 60;
    NSInteger second = (NSInteger)time % 60;

    return [NSString stringWithFormat:@"%02ld:%02ld", min, second];
}

三 旋轉動畫和進度完善

  • 給iconView添加旋轉動畫
- (void)addIconViewAnimation
{
    // 1.創建動畫(基本動畫)
    CABasicAnimation *rotationAnim = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];

    // 2.設置動畫的屬性
    rotationAnim.fromValue = @(0);
    rotationAnim.toValue = @(M_PI * 2);
    rotationAnim.duration = 40.0;
    rotationAnim.repeatCount = NSIntegerMax;

    // 3.添加到iconView的layer
    [self.iconView.layer addAnimation:rotationAnim forKey:nil];
}
  • 更新進度條,搞一個定時器
#pragma mark - 對定時器的操作
- (void)startProgressTimer
{
    [self updateProgress]; // 主動調用,防止1s間隔
    self.progressTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(updateProgress) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:self.progressTimer forMode:NSRunLoopCommonModes];
}

- (void)stopProgressTimer
{
    [self.progressTimer invalidate];
    self.progressTimer = nil;
}

- (void)updateProgress
{
    // 改變滑塊的位置
    self.slider.value = self.player.currentTime / self.player.duration;

    // 設置當前播放時間的Label的文字
    self.currentTimeLabel.text = [NSString stringWithTime:self.player.currentTime];
}

四 進度條事件處理

  • 滑動進度條需要以下幾個操作步驟:

    • 1.移除定時器
    • 2.滑動過程中改變當前播放時間
    • 3.用戶鬆手時播放當前時間對應音樂
  • 定時器移除代碼

- (void)stopProgressTimer
{
    [self.progressTimer invalidate];
    self.progressTimer = nil;
}
  • 根據滑動位置比例計算出當前時間
#pragma mark 滑塊的值改變
- (IBAction)sliderValueChange:(UISlider *)sender {
    // 1.進度條當前進度的比例
    CGFloat ratio = sender.value;

    // 2.根據當前的比例,計算當前的時間
    NSTimeInterval currentTime =  self.player.duration * ratio;

    // 3.改變currentTimeLabel的顯示的文字
    self.currentTimeLabel.text = [NSString stringWithTime:currentTime];
}
  • 用戶鬆手時播放當前位置對應時間的音樂
    • 注意:進度條想要監聽點擊需要添加一個手勢
#pragma mark 用戶結束點擊
- (IBAction)sliderTouchUpInside:(UISlider *)sender {
    // 1.改變歌曲播放的進度
    // 1.1.進度條當前進度的比例
    CGFloat ratio = sender.value;

    // 1.2.根據當前的比例,計算當前的時間
    NSTimeInterval currentTime =  self.player.duration * ratio;

    // 1.3.改變歌曲播放的時間
    self.player.currentTime = currentTime;

    // 2.添加定時器
    [self startProgressTimer];
}
  • 進度條的點擊
#pragma mark 進度條的點擊
- (IBAction)sliderClick:(UITapGestureRecognizer *)sender {
    // 1.獲取進度條的比例
    // 1.1.獲取用戶點擊的位置
    CGPoint point = [sender locationInView:sender.view];

    // 1.2.計算比例
    CGFloat ratio = point.x / self.slider.bounds.size.width;

    // 2.計算當前應該播放的時間
    NSTimeInterval currentTime = ratio * self.player.duration;

    // 3.改變歌曲播放的進度
    self.player.currentTime = currentTime;

    // 4.更新進度(定時器會有1s 間隔)
    [self updateProgress];
}

五 對歌曲控制的事件

  • 上一首
    • 抽取工具類方法
+ (GGMusic *)previousMusic
{
    // 1.取出當前歌曲的下標值
    NSUInteger currentIndex = [_musics indexOfObject:_playingMusic];

    // 2.計算上一個歌曲的下表
    NSInteger previousIndex = currentIndex - 1;
    if (previousIndex < 0) {
        previousIndex = _musics.count - 1;
    }

    // 3.取出上一個歌曲
    return [_musics objectAtIndex:previousIndex];
}
- (IBAction)previousMusic {
     // 0.取出當前歌曲
    GGMusic *playingMusic = [GGGMusicTool playingMusic];

    // 1.停止當前歌曲
    [GGAudioTool stopMusicWithMusicName:playingMusic.filename];

    // 2.取出下一首歌曲,並且播放
    GGMusic *previousMusic = [GGMusicTool previousMusic];
    [GGAudioTool playMusicWithMusicName:previousMusic.filename];

    // 3.設置上一首歌曲成爲當前播放的歌曲
    [GGMusicTool setPlayingMusic:previousMusic];

    // 4.改變界面信息成爲上一首歌曲的信息
    [self startPlayingMusic];
}
  • 下一首
+ (GGMusic *)nextMusic
{
    // 1.取出當前歌曲的下標值
    NSUInteger currentIndex = [_musics indexOfObject:_playingMusic];

    // 2.計算下一個歌曲的下表
    NSInteger nextIndex = currentIndex + 1;
    if (nextIndex > _musics.count - 1) {
        nextIndex = 0;
    }

    // 3.取出上一個歌曲
    return [_musics objectAtIndex:nextIndex];
}
  • 上一首和下一首代碼類似,抽成1個方法
- (void)switchMusicWithNextMusic:(BOOL)isNextMusic
{
    // 0.取出當前歌曲
    GGMusic *playingMusic = [GGMusicTool playingMusic];

    // 1.停止當前歌曲
    [GGAudioTool stopMusicWithMusicName:playingMusic.filename];

    // 2.取出下一首歌曲,並且播放
    GGMusic *changeMusic = nil;
    if (isNextMusic) {
        changeMusic = [GGMusicTool nextMusic];
    } else {
        changeMusic = [GGMusicTool previousMusic];
    }
    [GGAudioTool playMusicWithMusicName:changeMusic.filename];

    // 3.設置上一首歌曲成爲當前播放的歌曲
    [GGMusicTool setPlayingMusic:changeMusic];

    // 4.改變界面信息成爲上一首歌曲的信息
    [self startPlayingMusic];
}
  • 暫停/播放
    • 默認圖片是選中狀態
- (IBAction)playOrPauseMusic:(UIButton *)sender {
    // 1.改變按鈕的狀態
    sender.selected = !sender.isSelected;

    // 2.根據歌曲是否在播放,來決定暫停還是播放
    if (self.player.isPlaying) {
        [self.player pause];

        // 暫停動畫
        [self.iconView.layer pauseAnimate];

        // 停止進度定時器
        [self stopProgressTimer];
    } else {
        [self.player play];

        // 繼續動畫
        [self.iconView.layer resumeAnimate];

        // 添加進度定時器
        [self startProgressTimer];
    }
}
  • 暫停/繼續核心動畫根控制器沒什麼關係,抽取分類CALayer+GGAnimate
- (void)pauseAnimate
{
    CFTimeInterval pausedTime = [self convertTime:CACurrentMediaTime() fromLayer:nil];
    self.speed = 0.0;
    self.timeOffset = pausedTime;
}
- (void)resumeAnimate
{
    CFTimeInterval pausedTime = [self timeOffset];
    self.speed = 1.0;
    self.timeOffset = 0.0;
    self.beginTime = 0.0;
    CFTimeInterval timeSincePause = [self convertTime:CACurrentMediaTime() fromLayer:nil] - pausedTime;
    self.beginTime = timeSincePause;
}

六 添加歌詞的 View

  • 歌詞的 View 爲一個UIScrollView
    • 根據偏移量不同,變化 view 的透明度
      • 遵守UIScrollViewDelegate
 #pragma mark - 實現LrcView的代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 1.計算scrollView偏移量
    CGFloat offsetRatio = scrollView.contentOffset.x / scrollView.bounds.size.width;

    // 2.設置歌詞的Label和iconView的透明度
    self.iconView.alpha = 1 - offsetRatio;
    self.lrcLabel.alpha = 1 - offsetRatio;
}   
  • 歌詞展示用 tableview 實現GGLrcView

    • 初始化出來就是一個tableview
    - (instancetype)initWithCoder:(NSCoder *)aDecoder
    {
    if (self = [super initWithCoder:aDecoder]) {
        [self setupTableView];
    }
    return self;
    }
    • 添加 tableview
    - (void)setupTableView
    {
    // 1.創建tableView
    UITableView *tableView = [[UITableView alloc] init];
    self.tableView = tableView;
    
    // 2.添加到歌詞的View中
    [self addSubview:tableView];
    
    // 3.設置tableView的屬性
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 35;
    }
  • UIScrollView中使用 Autolayout

    • 注意點:添加約束,必須要多添加2個約束(距離右邊和下邊)
- (void)layoutSubviews
{
    [super layoutSubviews];

    // 給tableView添加約束
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_top);
        make.left.equalTo(self.mas_left).offset(self.bounds.size.width);
        make.height.equalTo(self.mas_height);
        make.width.equalTo(self.mas_width);

        make.bottom.equalTo(self.mas_bottom);
        make.right.equalTo(self.mas_right);
    }];

    // 清除tableView的背景顏色和邊線
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    // 設置tableView的上下的內邊距
    self.tableView.contentInset = UIEdgeInsetsMake(self.bounds.size.height * 0.5, 0, self.bounds.size.height * 0.5, 0);
}
  • 實現tableview 的數據源方法
#pragma mark - 實現tableView的數據源方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 20;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"LrcCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];

        // 設置cell的背景
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        // 設置label的屬性
        cell.textLabel.textColor = [UIColor whiteColor];
        cell.textLabel.font = [UIFont systemFontOfSize:14.0];
        cell.textLabel.textAlignment = NSTextAlignmentCenter;
    }

    cell.textLabel.text = @"測試數據123";

    return cell;
}

七 歌詞的解析

  • 字典轉模型(一句歌詞轉成模型)GGLrcLine
/** 顯示的歌詞文字 */
@property (nonatomic, copy) NSString *text;
/** 時間 */
@property (nonatomic, assign) NSTimeInterval time;
  • 模型對外提供下面方法
- (instancetype)initWithLrcString:(NSString *)lrcString
{
    if (self = [super init]) {
        // [01:20.74]想這樣沒擔憂 唱着歌 一直走
        NSArray *lrclineArray = [lrcString componentsSeparatedByString:@"]"];
        self.text = lrclineArray[1];
        self.time = [self timeWithString:[lrclineArray[0] substringFromIndex:1]];
    }
    return self;
}
  • 時間需要解析成秒,抽取爲方法
- (NSTimeInterval)timeWithString:(NSString *)timeString
{
    // 01:20.74
    NSArray *timeArray = [timeString componentsSeparatedByString:@":"];

    NSInteger min = [timeArray[0] integerValue];
    NSInteger second = [[timeArray[1] componentsSeparatedByString:@"."][0] integerValue];
    NSInteger haomiao = [[timeArray[1] componentsSeparatedByString:@"."][1] integerValue];

    return min * 60 + second + haomiao * 0.01;
}
+ (instancetype)lrcLineWithLrcString:(NSString *)lrcString
{
    return [[self alloc] initWithLrcString:lrcString];
}
  • 解析歌詞抽取工具類
+ (NSArray *)lrcToolWithLrcName:(NSString *)lrcName
{
    // 1.獲取歌詞的路徑
    NSString *filePath = [[NSBundle mainBundle] pathForResource:lrcName ofType:nil];

    // 2.讀取該文件中的歌詞
    NSString *lrcString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];

    // 3.獲取歌詞的數組
    NSArray *lrcArray = [lrcString componentsSeparatedByString:@"\n"];

    // 4.將一句歌詞轉成模型對象,放入到一個數組中
    NSMutableArray *tempArray = [NSMutableArray array];
    for (NSString *lrclineString in lrcArray) {
        // 4.1.過濾不需要的歌詞的行
        if ([lrclineString hasPrefix:@"[ti:"] || [lrclineString hasPrefix:@"[ar:"] || [lrclineString hasPrefix:@"[al:"] || ![lrclineString hasPrefix:@"["]) {
            continue;
        }

        // 4.2.解析每一句歌詞轉成模型對象
        GGLrcLine *lrcLine = [GGLrcLine lrcLineWithLrcString:lrclineString];

        [tempArray addObject:lrcLine];
    }

    return tempArray;
}
  • 重寫 set 方法
#pragma mark - 重寫setLrcName的方法
- (void)setLrcName:(NSString *)lrcName
{
    _lrcName = lrcName;

    // 解析歌詞
    self.lrcLines = [GGLrcTool lrcToolWithLrcName:lrcName];

    // 刷新列表
    [self.tableView reloadData];

    // 讓tableView滾動到最上面
    [self.tableView setContentOffset:CGPointMake(0, - self.tableView.bounds.size.height * 0.5) animated:YES];
}

八 將當前播放時間實時傳遞給LrcView

  • 建一個歌詞定時器
/** 歌詞的定時器 */
@property (nonatomic, strong) CADisplayLink *lrcTimer;
  • 對歌詞定時器的操作
#pragma mark 歌詞的定時器
- (void)startLrcTimer
{
    self.lrcTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(updateLrcInfo)];
    [self.lrcTimer addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}

- (void)stopLrcTimer
{
    [self.lrcTimer invalidate];
    self.lrcTimer = nil;
}

- (void)updateLrcInfo
{
    self.lrcView.currentTime = self.player.currentTime;
}
  • 拿到實時時間
    • 根據當前播放時間, 讓歌詞滾到正確的位置
#pragma mark - 重寫setCurrentTime方法
- (void)setCurrentTime:(NSTimeInterval)currentTime
{
    _currentTime = currentTime;

    // 找出需要顯示的歌詞
    NSInteger count = self.lrcLines.count;
    for (int i = 0; i < count; i++) {
        // 1.拿到i位置的歌詞
        GGLrcLine *currentLrcLine = self.lrcLines[i];

        // 2.拿出i+1位置的歌詞
        NSInteger nextIndex = i + 1;
        if (nextIndex >= count) return;
        GGLrcLine *nextLrcLine = self.lrcLines[nextIndex];

        // 3.當前時間大於i位置歌詞的時間並且小於i+1位置的歌詞的時間
        if (currentTime >= currentLrcLine.time && currentTime < nextLrcLine.time && self.currentIndex != i) {

            /*
            [01:03.45]你是我的小呀小蘋果兒 63.45 63.46  64.43 i 12
            [01:07.06]就像天邊最美的雲朵 67.06 13
            */
            // 計算i位置的IndexPath
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            NSIndexPath *previousPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];

            // 記錄i位置的下標
            self.currentIndex = i;

            // 刷新i位置的cell(播放時字體變大)
            [self.tableView reloadRowsAtIndexPaths:@[indexPath, previousPath] withRowAnimation:UITableViewRowAnimationNone];

            // 讓tableView的i位置的cell,滾動到中間位置
            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];

            // 設置外面的歌詞
            self.lrcLabel.text = currentLrcLine.text;
        }

        // 4.當正在播放某一個歌詞(self.currentIndex == i)
        if (self.currentIndex == i) {
            // 4.1.計算當前已經播放的比例
            CGFloat progress = (currentTime - currentLrcLine.time) / (nextLrcLine.time - currentLrcLine.time);

            // 4.2.告知當前的歌詞的Label進度
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
            GGLrcCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
            cell.lrcLabel.progress = progress;

            // 4.3.改變外面的歌詞Label的進度
            self.lrcLabel.progress = progress;
        }
    }
}
  • 刷新數據,播放時字體變大
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // 1.創建cell
    GGLrcCell *cell = [GGLrcCell lrcCellWithTableView:tableView];

    if (indexPath.row == self.currentIndex) {
        cell.lrcLabel.font = [UIFont systemFontOfSize:18.0];
    } else {
        cell.lrcLabel.font = [UIFont systemFontOfSize:14.0];
        cell.lrcLabel.progress = 0;
    }

    // 2.給cell設置數據
    GGLrcLine *lrcline = self.lrcLines[indexPath.row];
    cell.lrcLabel.text = lrcline.text;

    return cell;
}
  • 自定義 Label,實現 Label 按播放進度漸變

    • 重繪一下 Label
    - (void)drawRect:(CGRect)rect
    {
    [super drawRect:rect];
    
    CGRect drawRect = CGRectMake(0, 0, rect.size.width * self.progress, rect.size.height);
    
    [[UIColor greenColor] set];
    
    // UIRectFill(drawRect);
    // R = S * Da   S是現在正在畫的內容透明爲1,Da 之前 label 內容的透明度
    UIRectFillUsingBlendMode(drawRect, kCGBlendModeSourceIn); // 文字漸變
    }
    • 實時調用
    - (void)setProgress:(CGFloat)progress
    {
    _progress = progress;
    
    [self setNeedsDisplay];
    }
  • 將Label 添加到 cell 中GGLrcCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        // 1.創建自定義的Label
        GGLrcLabel *lrcLabel = [[GGLrcLabel alloc] init];
        // 2.添加cell中
        [self.contentView addSubview:lrcLabel];
        // 3.給自定義的label添加約束
        [lrcLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self.contentView);
        }];
        // 4.設置label的屬性
        lrcLabel.textColor = [UIColor whiteColor];
        lrcLabel.font = [UIFont systemFontOfSize:14.0];
        // 5.設置cell的屬性
        self.backgroundColor = [UIColor clearColor];
        self.selectionStyle = UITableViewCellSelectionStyleNone;
        // 6.讓成員屬性的lrcLabel指向對象
        self.lrcLabel = lrcLabel;
    }
    return self;
}
  • 播放頁面顯示歌詞
// 歌詞的Label
@property (weak, nonatomic) IBOutlet GGLrcLabel *lrcLabel;

// 5.將外面顯示歌詞的Label的對象,賦值給lrcView的引用
    self.lrcView.lrcLabel = self.lrcLabel;

注意:切換歌曲,刷新 i 位置的 cell 時會報錯(上一首歌詞量與下一首歌詞量不同)

     // 計算i位置的IndexPath
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];

        NSArray *indexPaths = nil;
        if (self.currentIndex >= count) {
             indexPaths = @[indexPath];
         } else {
             NSIndexPath *previousPath = [NSIndexPath indexPathForRow:self.currentIndex inSection:0];
             indexPaths = @[indexPath, previousPath];
    }

九 音樂後臺播放

  • 1.開啓後臺模式
    這裏寫圖片描述

  • 2.設置音頻會話模式

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // 1.獲取音頻會話
    AVAudioSession *session = [AVAudioSession sharedInstance];

    // 2.設置音頻會話的類型
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];

    // 3.激活音頻會話(靜音狀態依然可以播放)
    [session setActive:YES error:nil];

    return YES;
}
  • 設置鎖屏界面
#pragma mark - 設置鎖屏界面的信息
- (void)setupLockScreenInfo
{
    // 1.拿到當前播放的歌曲
    GGMusic *playingMusic = [GGMusicTool playingMusic];

    // 2.設置鎖屏界面的內容
    // 2.1.獲取鎖屏界面中心
    MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];

    // 2.2.設置顯示的信息
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    // 2.2.1.設置歌曲名稱
    [dict setValue:playingMusic.name forKey:MPMediaItemPropertyAlbumTitle];
    // 2.2.2.設置歌手名稱
    [dict setValue:playingMusic.singer forKey:MPMediaItemPropertyArtist];
    // 2.2.3.設置專輯封面
    UIImage *image = [UIImage imageNamed:playingMusic.icon];
    MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
    [dict setValue:artwork forKey:MPMediaItemPropertyArtwork];
    // 2.2.4.設置歌曲的總時長
    [dict setValue:@(self.player.duration) forKey:MPMediaItemPropertyPlaybackDuration];
    infoCenter.nowPlayingInfo = dict;

    // 2.3.讓應用程序可以接受遠程事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}
  • 處理遠程事件
- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:
            [self playOrPauseMusic:self.playOrPauseBtn];
            break;

        case UIEventSubtypeRemoteControlNextTrack:
            [self nextMusic];
            break;

        case UIEventSubtypeRemoteControlPreviousTrack:
            [self previousMusic];
            break;
        default:
            break;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章