11

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?

lammert
  • 1,456
  • 14
  • 20
  • 3
    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 Sep 20 '15 at 19:14
  • 2
    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 Sep 20 '15 at 19:42
  • @lammert would u find anything related this? Please suggest me how it works in ios 8 and later specially for silent mode – Abha Nov 16 '15 at 10:13
  • @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 Jan 29 '16 at 19:37
  • @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 May 29 '19 at 07:39

2 Answers2

5

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!

Bright
  • 5,699
  • 2
  • 50
  • 72
  • @user3427013 isn't this code supposed to keep the sound playing? if you want to stop, do `AudioPlayer.stop()` – Bright Sep 10 '17 at 04:14
0

For Swift 3.2:

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