首页 > 解决方案 > iOS 14 在后台播放视频中的音频

问题描述

iOS 14 在后台播放视频中的音频:当应用程序进入后台时音频暂停(即使我在 Capability 中打开了后台模式)。

如果 avPlayer 在前台播放,用户按下设备锁定按钮,它就会发生。

标签: ios14background-audio

解决方案


如果您正在使用 avplayer 播放视频,并且还想在应用程序处于后台时播放音频。

试试这个代码,它适用于我的机器:

  • Xcode 版本:12.0
  • iOS版本:iOS 14
//first, observe the relative notification
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillResignActive:)
                                                 name:UIApplicationWillResignActiveNotification object:nil];

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(applicationWillEnterForeground:)
                                                 name:UIApplicationWillEnterForegroundNotification object:nil];


    //Add an observer to AVPlayerItem,this is the key point!!!
    [playerItem addObserver:self forKeyPath:@"playbackLikelyToKeepUp" options:NSKeyValueObservingOptionNew context:nil];

-(void)applicationWillResignActive:(NSNotification *)notification{
    //1 make sure the category of AVAudioSession is AVAudioSessionCategoryPlayback
    AVAudioSession *session=[AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback  error:nil];
    [session setActive:YES error:nil];
    
    //2 This is important!!!
    //set the avplayerlayer.player = nil.
    mavPlayerLayer.player = nil;
}


//when app becomes active,we should add the player to the avplayerlayer.
-(void)applicationWillEnterForeground:(NSNotification *)notification{
    // restore the avPlayerLayer.player
    mavPlayerLayer.player = mavPlayer;
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"playbackLikelyToKeepUp"]) {
        NSLog(@"playbackLikelyToKeepUp");
        [mavPlayer play];
    }
}


当然,不要忘记在 info.plist 文件中添加相关属性以支持后台播放。

信息列表


推荐阅读