iOS常用

iOS开发音频后台播放配置和锁屏信息

2021-03-19  本文已影响0人  Flynn_Lee

1、后台播放配置


image.png

2、AppDelegate.m代码配置

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [self setBackgroundPlayMusic];
    return YES;
}
#pragma mark - UISceneSession 
-(void)setBackgroundPlayMusic
{
    //获取音频会话
    AVAudioSession *session = [AVAudioSession sharedInstance];
   //设置后台播放
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    //激活会话
    [session setActive:YES error:nil];
}

3、锁屏信息和锁屏界面控制

///设置锁屏信息
-(void)setLockScreenInfo
{
    // MPMediaItemPropertyAlbumTitle
    // MPMediaItemPropertyAlbumTrackCount
    // MPMediaItemPropertyAlbumTrackNumber
    // MPMediaItemPropertyArtist
    // MPMediaItemPropertyArtwork
    // MPMediaItemPropertyComposer
    // MPMediaItemPropertyDiscCount
    // MPMediaItemPropertyDiscNumber
    // MPMediaItemPropertyGenre
    // MPMediaItemPropertyPersistentID
    // MPMediaItemPropertyPlaybackDuration
    // MPMediaItemPropertyTitle

    //获取锁屏中心
    MPNowPlayingInfoCenter *playCenter = [MPNowPlayingInfoCenter defaultCenter];
    
    NSMutableDictionary *infoDict = [NSMutableDictionary dictionary];
    //设置歌曲名
    infoDict[MPMediaItemPropertyAlbumTitle] = self.VModel.currentModel.name;
    //设置歌手名
    infoDict[MPMediaItemPropertyArtist] = self.VModel.currentModel.singer;
    //设置图片
    MPMediaItemArtwork *artWork = [[MPMediaItemArtwork alloc]initWithImage:[UIImage imageNamed:self.VModel.currentModel.icon]];
    
    infoDict[MPMediaItemPropertyArtwork] = artWork;
    //设置总时长
    infoDict[MPMediaItemPropertyPlaybackDuration] = @(self.player.duration);
    
    playCenter.nowPlayingInfo = infoDict;
    //开启远程控制
    [[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
}

///远程控制
-(void)remoteControlReceivedWithEvent:(UIEvent *)event
{
//    UIEventSubtypeRemoteControlPlay                 = 100,
//    UIEventSubtypeRemoteControlPause                = 101,
//    UIEventSubtypeRemoteControlStop                 = 102,
//    UIEventSubtypeRemoteControlTogglePlayPause      = 103,
//    UIEventSubtypeRemoteControlNextTrack            = 104,
//    UIEventSubtypeRemoteControlPreviousTrack        = 105,
//    UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
//    UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
//    UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
//    UIEventSubtypeRemoteControlEndSeekingForward    = 109,
    
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:
            [self play:self.playButton];
            break;
        case UIEventSubtypeRemoteControlNextTrack:
        
            [self next:nil];
            break;
        case UIEventSubtypeRemoteControlPreviousTrack:
        
            [self previous:nil];
            break;
        default:
            break;
    }
    
    
}
上一篇下一篇

猜你喜欢

热点阅读