Search code examples
iosavfoundationavplayeravaudioplayeravaudiosession

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


When I play an m3u8 on an AVQueuePlayer with setting the player mute, the music from another app in the background stops. I did not set AudioSession category and session as shown in the sample code.

Does the AVQueuePlayer set AudioSession category and session by default when I do replaceCurrentItemWithPlayerItem? Or how does the background music stops?

#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

Solution

  • you should use [AVAudioSession setCategory:withOptions:error:] method https://developer.apple.com/documentation/avfoundation/avaudiosession/1616442-setcategory?language=objc

    make sure to use AVAudioSessionCategoryOptionMixWithOthers option.

    for example:

    [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback withOptions: AVAudioSessionCategoryOptionMixWithOthers error: nil];

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