Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVPlayer removes background music

Tags:

ios

avplayer

I've been using giffycat to decode, store, and play gifs in my app. I am making it so that it can easily load a gif in a UICollectionView's cell, so I have decided for each gif model to have its own AVPlayer. I have noticed that simply by creating an AVPlayer, shown bellow, audio from other apps is killed! Annoying for both the user and the creater!

// Create an AVURLAsset with an NSURL containing the path to the video
AVURLAsset *asset = [AVURLAsset URLAssetWithURL:[NSURL URLWithString:_mp4] options:nil];
// Create an AVPlayerItem using the asset
AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
_player = [AVPlayer playerWithPlayerItem:item]; //if this line is commented out, I hear audio, else audio from Spotify is quickly killed...

Since these videos are just gifs, I am wondering if there is some way to unassign the audio session. I do not know much about this. ples help!

like image 899
Ethan Avatar asked Aug 09 '14 06:08

Ethan


1 Answers

Turns out the answer is pretty easy, after a little googling and documentation reading... The solution is

// audio session
let audioSession = AVAudioSession.sharedInstance()
try! audioSession.setCategory(AVAudioSessionCategoryAmbient,
  withOptions: AVAudioSessionCategoryOptions.MixWithOthers)

oops, just realized I am posting my question in objC and answer in Swift. Well tough, because that's life sometimes.

AudioSession is a singleton for your entire app to rule how your application mingles with the other sounds of the system and other apps! The default audio session is

  1. playback is enabled, recording is disabled
  2. when user moves silent switch to "silent" your audio is silenced
  3. when user presses sleep/wake button to lock screen or auto-lock period expires, your audio is silenced
  4. when your audio starts, other audio on device (music) is silenced.

CategoryAmbient tells it not to do 4

Nice documentation! https://developer.apple.com/library/ios/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/ConfiguringanAudioSession/ConfiguringanAudioSession.html#//apple_ref/doc/uid/TP40007875-CH2-SW1

like image 160
Ethan Avatar answered Sep 18 '22 21:09

Ethan