11
votes

In iOS 9 (Xcode 7, Swift 2.0) I'm trying to play a sound in silent mode using the following code:

try! AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: .MixWithOthers)
try! AVAudioSession.sharedInstance().setActive(true)
AudioServicesPlayAlertSound(1005)

According to other answers and Apple's documentation I thought this should work but it doesn't play a sound on iOS 9 when in silent mode. It does play it when not in silent mode. From Apple's doc:

AVAudioSessionCategoryPlayback -- Playback only. Plays audio even with the screen locked and with the Ring/Silent switch set to silent. Use this category for an app whose audio playback is of primary importance.

Am I missing something here or is there a other/new way to get this to work?

2
I hope it doesn't work. If I put my phone in silent mode then I don't want apps making sounds. That's the point of silent mode.rmaddy
From Apple's doc this should be possible. And I'm using it for a timer app in which case it should even play when the phone is in silent mode because it is of primary importance.lammert
@lammert would u find anything related this? Please suggest me how it works in ios 8 and later specially for silent modeAbha
@lammert Not sure what is going on here but this definitely can work (just tested it out). I would suspect there is a different problem at work here. Have you tried using your own audio file?Firo
@rmaddy what if you want everything muted but this app? Let's say to help you at work somehow? Imagine you are a baker and you don't want to be disturbed but you want your baking app to set alarms for the multiple stuff you are baking. If the app is annoying people will just uninstall it.Dpedrinha

2 Answers

5
votes

This is my code:

do {
    try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: AVAudioSessionCategoryOptions.MixWithOthers)
    }
catch {
        // report for an error
    }

AudioPlayer.play()

It works on my iPhone.

Good luck!

0
votes

For Swift 3.2:

do {
        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.duckOthers)
    }
    catch {
        // report for an error
    }