18

So I've just noticed that on my iPod Touch, when my app triggers a short wav file to play using AVAudioPlayer, the music gets paused. Is this normal?

I can't find any reference to this, and it seems like it would be noted somewhere. Is there a way to keep the music going while I play my sounds?

Matthieu Brucher
  • 21,634
  • 7
  • 38
  • 62
Kenny Winker
  • 11,919
  • 7
  • 56
  • 78

4 Answers4

81

Basically, every app is assigned an audio session which is modelled as a singleton class which you can get at application launch and set parameters to. The way I fixed the same problem was through a single line of code placed at applicationDidFinishLaunching:

Objective-C:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];

Swift 2/3:

try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
Iulian Onofrei
  • 9,188
  • 10
  • 67
  • 113
Michael M
  • 931
  • 1
  • 8
  • 3
13

Note: The AudioSession API has been completely deprecated in iOS 7.0

You can't run AVAudioPlayer and the iPod player or MPMusicPlayer or MPMoviePlayer at the same time, without doing a bit more work. If you want easy, then use Audio Toolbox's System Sounds.

If you want to do some extra work, then you should look at Audio Sessions:

kAudioSessionCategory_UserInterfaceSoundEffects For sound effects such as touch feedback, explosions, and so on.

Equivalent to the kAudioSessionCategory_AmbientSound category, which you should use instead. The kAudioSessionCategory_UserInterfaceSoundEffects category is deprecated in iPhone OS 3.0.

kAudioSessionCategory_AmbientSound For long-duration sounds such as rain, car engine noise, and so on. It is also for “play along” style applications, such a virtual piano that a user plays over iPod audio.

When you use this category, audio from built-in applications, such as the iPod, mixes with your audio. Your audio is silenced when the Ring/Silent switch is set to silent or when the screen locks.

Richard Stelling
  • 25,607
  • 27
  • 108
  • 188
mahboudz
  • 39,196
  • 16
  • 97
  • 124
0

Depending on your requirements, playing system sounds might not be enough, take a look at the session options, e.g. MixWithOthers

struct AVAudioSessionCategoryOptions : OptionSetType {
    init(rawValue rawValue: UInt)
    static var MixWithOthers: AVAudioSessionCategoryOptions { get }
    static var DuckOthers: AVAudioSessionCategoryOptions { get }
    static var AllowBluetooth: AVAudioSessionCategoryOptions { get }
    static var DefaultToSpeaker: AVAudioSessionCategoryOptions { get }
    static var InterruptSpokenAudioAndMixWithOthers: AVAudioSessionCategoryOptions { get }
}

When you start your session, pass the MixWithOthers option, maybe the DuckOthers (will drop the ipod volume when your sound plays) is another option.

some_id
  • 29,466
  • 62
  • 182
  • 304
0

Swift 5 equivalent:

try? AVAudioSession.sharedInstance().setCategory(.ambient)