为什么在未激活 AudioSession 的情况下播放 AVPlayer/AVQueuePlayer 时背景音乐会停止?

Why does background music stops when playing an AVPlayer/AVQueuePlayer without setting AudioSession active?

当我在设置了播放器静音的 AVQueuePlayer 上播放 m3u8 时,后台另一个应用程序的音乐停止了。我没有按照示例代码设置 AudioSession 类别和会话。

我做的时候AVQueuePlayer是不是默认设置了AudioSession类别和会话replaceCurrentItemWithPlayerItem?或者背景音乐怎么停?

#import "ViewController.h"
@import AVFoundation;

@interface ViewController ()
@property (nonatomic, nonnull) AVQueuePlayer * player;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.player = [[AVQueuePlayer alloc] init];
    [self.player setMuted:YES];
    NSURL *URL = [NSURL URLWithString:@"https://bitdash-a.akamaihd.net/content/MI201109210084_1/m3u8s/f08e80da-bf1d-4e3d-8899-f0f6155f6efa.m3u8"];
//        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
//        [[AVAudioSession sharedInstance] setActive:NO error:nil];
    AVPlayerItem * item = [AVPlayerItem playerItemWithURL:URL];
    [self.player replaceCurrentItemWithPlayerItem:item];

    [self.player play];
    // Do any additional setup after loading the view.
}


@end

你应该使用 [AVAudioSession setCategory:withOptions:error:] 方法 https://developer.apple.com/documentation/avfoundation/avaudiosession/1616442-setcategory?language=objc

确保使用 AVAudioSessionCategoryOptionMixWithOthers 选项。

例如:

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback withOptions: AVAudioSessionCategoryOptionMixWithOthers 错误:无];

[[AVAudioSession sharedInstance] setActive:NO error:nil];