Prevent AVPlayer cancel background sound

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

Is there a way to play video using AVPlayer and not cancel the 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!

+4
source share
3 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) } 
+8
source

You need to set an option for an audio session in order to mix the session with others:

 NSError *error; if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&error]) { NSLog(@"audio session error: %@", error); } 
+3
source

I was able to solve this using the GeneratorOfOne comment. The only thing I needed was to run this 2 lines of code before running player.play ...

 AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: &error) AVAudioSession.sharedInstance().setActive(true, error: &error) 
+1
source

All Articles