【iOS】实现类似QQ后台音乐播放功能

创建播放器

	@property (nonatomic, strong)AVPlayer *player;


	self.player = [[AVPlayer alloc] init];
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://atyk.jzhunk.xyz/v130/upload/1.mp3"]];
    [self.player replaceCurrentItemWithPlayerItem:playerItem];
    

播放

#pragma mark - 开始播放
- (void)playMusic
{
    if (!self.player) {
        return;
    }
    
    [self.player play];
    [self updateLockScreenInfo];
}

暂停

#pragma mark - 暂停播放
- (void)pauseMusic
{
    if (!self.player) {
        return;
    }
    
    [self.player pause];
    
    [self updateLockScreenInfo];
}

拖动到某个时间

#pragma mark - 拖动到某个时间
- (void)seekToTime:(NSTimeInterval)time {
    
    CMTime duration = _player.currentItem.duration;
    CMTime currentTime = CMTimeMakeWithSeconds(time, duration.timescale);
    
    [_player seekToTime:currentTime completionHandler:^(BOOL finished) {
        // 同步锁屏界面进度
        [self updateLockScreenInfo];
    }];
}

播放完毕

    __weak __typeof__(self) weakSelf = self;
    [self.player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(1, NSEC_PER_SEC) queue:NULL usingBlock:^(CMTime time) {
        //进度 当前时间/总时间
        CGFloat progress = CMTimeGetSeconds(weakSelf.player.currentItem.currentTime) / CMTimeGetSeconds(weakSelf.player.currentItem.duration);
        NSLog(@"进度 == %f", progress);
        if (progress == 1.0f) {
            NSLog(@"播放完毕");
            //播放百分比为1表示已经播放完毕
            //接着播放下一条录音
            AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://atyk.jzhunk.xyz/v130/upload/1.mp3"]];
            [weakSelf.player replaceCurrentItemWithPlayerItem:playerItem];
            [weakSelf playMusic];
        }
    }];

更新锁屏界面信息

#pragma mark - 更新锁屏界面信息
- (void)updateLockScreenInfo {
    
    if (!self.player) {
        return;
    }
    
    // 1.获取锁屏中心
    MPNowPlayingInfoCenter *playingInfoCenter = [MPNowPlayingInfoCenter defaultCenter];
    // 初始化一个存放音乐信息的字典
    NSMutableDictionary *playingInfoDict = [NSMutableDictionary dictionary];
    
    // 2、设置歌曲名
    [playingInfoDict setObject:[NSString stringWithFormat:@"歌曲1111"]
                        forKey:MPMediaItemPropertyTitle];
    [playingInfoDict setObject:[NSString stringWithFormat:@"专辑2222"]
                        forKey:MPMediaItemPropertyAlbumTitle];
    
    
    // 3、设置封面的图片
    UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"cover.jpg"]];
    if (image) {
        MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
        [playingInfoDict setObject:artwork forKey:MPMediaItemPropertyArtwork];
    }
    
    NSLog(@"总共时间 %@", @(CMTimeGetSeconds(_player.currentItem.duration)));
    NSLog(@"当前时间 %@", @(CMTimeGetSeconds(_player.currentItem.currentTime)));
    // 4、设置歌曲的时长和已经消耗的时间
    NSNumber *playbackDuration = @(CMTimeGetSeconds(_player.currentItem.duration));
    NSNumber *elapsedPlaybackTime = @(CMTimeGetSeconds(_player.currentItem.currentTime));
    
    if (!playbackDuration || !elapsedPlaybackTime) {
        return;
    }
    [playingInfoDict setObject:playbackDuration
                        forKey:MPMediaItemPropertyPlaybackDuration];
    [playingInfoDict setObject:elapsedPlaybackTime
                        forKey:MPNowPlayingInfoPropertyElapsedPlaybackTime];
    [playingInfoDict setObject:@(_player.rate) forKey:MPNowPlayingInfoPropertyPlaybackRate];
    
    //音乐信息赋值给获取锁屏中心的nowPlayingInfo属性
    playingInfoCenter.nowPlayingInfo = playingInfoDict;
}

添加锁屏按钮远程控制

#pragma mark - 添加远程控制
- (void)createRemoteCommandCenter
{
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];

    MPRemoteCommand *pauseCommand = [commandCenter pauseCommand];
    [pauseCommand setEnabled:YES];
    [pauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"暂停");
        [self pauseMusic];
        return MPRemoteCommandHandlerStatusSuccess;
    }];

    MPRemoteCommand *playCommand = [commandCenter playCommand];
    [playCommand setEnabled:YES];
    [playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"开始");
        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://atyk.jzhunk.xyz/v130/upload/1.mp3"]];
        [self.player replaceCurrentItemWithPlayerItem:playerItem];
        [self playMusic];
        return MPRemoteCommandHandlerStatusSuccess;
    }];

    MPRemoteCommand *nextCommand = [commandCenter nextTrackCommand];
    [nextCommand setEnabled:YES];
    [nextCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"下一首");
        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://atyk.jzhunk.xyz/v130/upload/1.mp3"]];
        [self.player replaceCurrentItemWithPlayerItem:playerItem];
        [self playMusic];
        return MPRemoteCommandHandlerStatusSuccess;
    }];

    MPRemoteCommand *previousCommand = [commandCenter previousTrackCommand];
    [previousCommand setEnabled:YES];
    [previousCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"上一首");
        AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:@"http://atyk.jzhunk.xyz/v130/upload/1.mp3"]];
        [self.player replaceCurrentItemWithPlayerItem:playerItem];
        [self playMusic];
        return MPRemoteCommandHandlerStatusSuccess;
    }];

    MPRemoteCommand *changePlaybackPositionCommand = [commandCenter changePlaybackPositionCommand];
    [changePlaybackPositionCommand setEnabled:NO];
    [changePlaybackPositionCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        NSLog(@"设置播放位置/进度");
        MPChangePlaybackPositionCommandEvent * playbackPositionEvent = (MPChangePlaybackPositionCommandEvent *)event;
        [self seekToTime:playbackPositionEvent.positionTime];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
}

监听前台/后台

    // 后台通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(apllicationWillResignActiveNotification:) name:UIApplicationWillResignActiveNotification object:nil];
    // 进入前台通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(apllicationWillEnterForegroundNotification:) name:UIApplicationWillEnterForegroundNotification object:nil];

	// 移除监听
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
 	// 移除监听
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
/// 进入后台
- (void) apllicationWillResignActiveNotification:(NSNotification *)n
{
    NSError *error = nil;
    // 后台播放代码
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:&error];
    if(error) {
        NSLog(@"ListenPlayView background error0: %@", error.description);
    }
    [session setCategory:AVAudioSessionCategoryPlayback error:&error];
    if(error) {
        NSLog(@"ListenPlayView background error1: %@", error.description);
    }
    /// 进后台 设置接收远程控制
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
}

/// 进入前台通知
- (void) apllicationWillEnterForegroundNotification:(NSNotification *)n {
    // 进前台 设置不接受远程控制
    [[UIApplication sharedApplication] endReceivingRemoteControlEvents];
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值