0

I have a project where it is required to play a sound when the phone is in silent mode. This was possible in earlier versions of iOS, but it is not in iOS 8 or later using standard APIs.

I am now looking for a possibility to do this using a private API, I have looked thru the header files but I have not found the right one. I would guess an API like this exists but I don't know which. Any suggestions are appreciated.

Please note that solutions that make the play and pause button show is not acceptable. Please also note that I am looking for a private API and I am aware of all issues related to the fact that I am using private APIs. Furthermore playing a sound when the user has set the silent switch to on can make users angry in some cases, but in this case they will be angry if there is no sound (think alarm clock).

EDIT: Will need to do this from background, for example when receiving a push notification.

www.jensolsson.se
  • 3,023
  • 2
  • 35
  • 65

1 Answers1

1

You did not specify language so I will just use Swift. The code is not really protected well but basically you need to set the AVAudioSession singleton's category to AVAudioSessionCategoryPlayback:

try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)

// Then just play the file
guard let soundPath = NSBundle.mainBundle().pathForResource("sound", ofType: "wav") else {
    // bad path
    return
}

var soundFile = NSURL.fileURLWithPath(soundPath)

// Instance variable
player = try AVAudioPlayer(contentsOfURL: soundFile)
player.play()
Firo
  • 15,448
  • 3
  • 54
  • 74
  • Thanks for the reply. 2 questions. I have already set the audiosession to AVAudioSessionCategoryPlayAndRecord for other purposes. I guess I can't do AVAudioSessionCategoryPlayAndRecord|AVAudioSessionCategoryPlayback ? Second question, wouldnt this show the play and pause buttons? I also forgot to mention that I need to do this from background. – www.jensolsson.se Jan 29 '16 at 19:23
  • 1. No, you cannot do that as this is just a string. But you could maybe change out which category it is using depending on immediate needs? Not sure your specific use case though. -- -- -- 2. Not in any of my testing. It is not even pause-able via the slide up menu. – Firo Jan 29 '16 at 19:29