Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent AVPlayer from canceling background audio

In my app I use AVPlayer to play simple videos. These videos do not have any audio track. The problem is that when I play them, all background music (not from my app) is stopped. How do I prevent this?

Is there a way to play videos with AVPlayer and not cancel background music?

My code is:

let urlAsset = AVURLAsset(URL: urlLocal, options: nil)
let item = AVPlayerItem(asset: urlAsset)
self.videoPlayer = AVPlayer(playerItem: item)

if let player = self.videoPlayer {
    self.videoLayer = AVPlayerLayer(player: player)
    if let layer = self.videoLayer {

        layer.frame = self.view.bounds
        self.view.layer.addSublayer(layer)

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "videoPlayerDidReachEnd:", name: AVPlayerItemDidPlayToEndTimeNotification , object: nil)

        player.actionAtItemEnd = AVPlayerActionAtItemEnd.None
        player.play()
    }
}

Thanks!

like image 745
animal_chin Avatar asked Jul 28 '15 08:07

animal_chin


2 Answers

Swift 3 with some error handling:

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
} catch let error as NSError {
    print(error)
}

do {
    try AVAudioSession.sharedInstance().setActive(true)
} catch let error as NSError {
    print(error)
}
like image 136
Alfie Hanssen Avatar answered Oct 11 '22 13:10

Alfie Hanssen


You need to set option for audio session to mix your session with others:

NSError *error;
if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error])
{
    NSLog(@"audio session error: %@", error);
}
like image 29
John Tracid Avatar answered Oct 11 '22 13:10

John Tracid