Search code examples
swiftaudio

Starting audio in locked screen mode not working


I am working on a timer App with alerts. When the screen is locked I would like to have my alerts/Text To Speech keeping to work. It works for some time between 30 to 60 sec and then alerts stops working but the timer is continuing to work as when I unlock the phone the timer progressed and works. I went through many posts and I didn't find a solution. It looks like new audio cannot be fired in lock down mode (some posts said new audio sounds cannot be triggered in lock down but continuity of audio is working). I finally found this post -> AVFoundation playing audio in background/on lock screen in Swift

so I added following lines in my code:

    // to authorize background music in parallel
    try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.ambient)
    try? AVAudioSession.sharedInstance().setActive(true)

    // to play audio in background, lock screen mode
    try? AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)

and in info.plist I have this entry:

enter image description here

The result is that short audio sounds are working (I trigger them every 30 sec) only if I lock the screen during an audio, if I do it between two sounds it stops. I spent many days on searching solutions but nothing works, can someone please help here?

Spending again some hours to search further on this topic and what I found: -> https://developer.apple.com/forums/thread/77937

seems really a problem for many people but I don't understand why we don't find any solution as I saw many apps with this feature working, if you see any good answer please tell me.


Solution

  • As no one had an answer I contacted Apple Developer Technical Support and the response was a bit surprising but there is no "clean way" to do it, here the answer I got: "To continue playing audio from the background, continuously play audio in the background (mostly this will be silent, except for when you have a new “alert”)" I tested it with a silent.wav file of 60 sec that I fire every 55 sec and it works!