简体   繁体   中英

AVPlayer removes background music

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!

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

在从中创建AVPlayer之前,将AVPlayerItem的audioMix属性设置为nil,以从资产中删除音轨。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM