7

I use AVAudioPlayer to play sounds in my app, but it turns off the iPod when a sound plays.

Is there a way to prevent this? I don't want to use System Sounds because I can't control their volume.

Thanks for your help.

Andrew Johnson
  • 13,108
  • 13
  • 75
  • 116

1 Answers1

15

This should work for you (taken from my Ambiance app)

[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 1;
AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doSetProperty), &doSetProperty);
[[AVAudioSession sharedInstance] setActive: YES error: nil];

From the docs:

kAudioSessionProperty_OverrideCategoryMixWithOthers Changes the mixing behavior of the kAudioSessionCategory_MediaPlayback and kAudioSessionCategory_PlayAndRecord audio session categories. Setting this property to TRUE (any nonzero value) allows mixing of iPod audio with application audio. Other aspects of these categories, such as their Ring/Silent switch behavior, are not affected.

This property has value of FALSE (0) by default. When the audio session category changes, such as during an interruption, the value of this property reverts to FALSE. To regain mixing behavior you must then re-set this property.

Always check to see if setting this property succeeds or fails, and react appropriately; behavior may change in future releases of iPhone OS.

Available in iPhone OS 3.0 and later.

Declared in AudioServices.h.

coneybeare
  • 33,113
  • 21
  • 131
  • 183
  • 1
    Put this in the app delegate. Worked fine for me. Have fun, fellow googlers ;) – August Lilleaas Feb 23 '11 at 18:36
  • 2
    Tremendous! Thanks! For other beginners like me: to get this to link you need to do #import and to link the AudioToolbox framework. For help on how to do that in XCode 4.2, look here: http://stackoverflow.com/questions/3352664/how-to-add-existing-frameworks-in-xcode-4 – Andy Weinstein Jun 06 '12 at 07:03
  • Is this still the best way to accomplish this in iOS 7? – MattLoszak Aug 19 '13 at 16:27
  • @MattLoszak I would ask this in the devforums as iOS 7 is under NDA – coneybeare Aug 21 '13 at 13:45
  • It's deprecated since iOS7 – Stéphane de Luca Dec 21 '13 at 19:19
  • For those looking for workarounds: AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers) – lm2s May 21 '16 at 13:37
  • since iOS7: `[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];` – nghien_rbc Aug 02 '16 at 09:34