iOS開發--QQ音樂練習,後臺播放和鎖屏界面

一.設置後臺播放session

  • 首先容許程序後臺播放
  • 代碼實現
     1 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     2     
     3     // 設置後臺播放的代碼,步驟
     4     // 1.獲取音頻的會話
     5     AVAudioSession *session = [AVAudioSession sharedInstance];
     6     // 2.設置後臺播放類型
     7     [session setCategory:AVAudioSessionCategoryPlayback error:nil];
     8     // 3.激活會話
     9     [session setActive:YES error:nil];
    10     
    11     return YES;
    12 }

     

二.鎖屏界面app

  • 適當的時機調用這個方法                                                                              
    #pragma mark - 設置鎖屏界面的信息
    - (void)setupLockScreenInfo
    {
        // 1.獲取當前正在播放的歌曲
        ChaosMusic *playingMusic = [ChaosMusicTool playingMusic];
        // 2.獲取鎖屏界面中心
        MPNowPlayingInfoCenter *playingCenter = [MPNowPlayingInfoCenter defaultCenter];
        // 3.設置展現的信息
        NSMutableDictionary *playingInfo = [NSMutableDictionary dictionary];
        
        playingInfo[MPMediaItemPropertyAlbumTitle] = playingMusic.name;
        playingInfo[MPMediaItemPropertyArtist] = playingMusic.singer;
        MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:playingMusic.icon]];
        playingInfo[MPMediaItemPropertyArtwork] = artwork;
        playingInfo[MPMediaItemPropertyArtist] = @(self.player.currentTime);
        
        playingCenter.nowPlayingInfo = playingInfo;
        // 4.讓應用程序能夠接受遠程事件
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    }

     

  • 實現了鎖屏界面,沒有實現監聽遠程事件的話,鎖屏界面的下一首之類的按鈕沒有反應.實現下面的方法
     1 // 監聽遠程事件
     2 - (void)remoteControlReceivedWithEvent:(UIEvent *)event
     3 {
     4     switch (event.subtype) {
     5         case UIEventSubtypeRemoteControlPlay:
     6         case UIEventSubtypeRemoteControlPause:
     7             [self startOrPause:nil];
     8             break;
     9             
    10         case UIEventSubtypeRemoteControlNextTrack:
    11             [self nextMusic:nil];
    12             break;
    13             
    14         case UIEventSubtypeRemoteControlPreviousTrack:
    15             [self previousMusic:nil];
    16             break;
    17             
    18         default:
    19             break;
    20     }
    21 }
相關文章
相關標籤/搜索