Andrew
Andrew

Reputation: 16051

App not playing sound when screen turned off, but doing everything else as it should?

I have an alarm clock app which works on a timer. When the alarm is meant to go off and the screen is switched off, it should start playing audio from AVAudioPlayer, but it doesn't. Then when i turn the screen back on, i can see that the rest of the code fired as expected (a stop button is now on the screen). How do i get the AVAudioPlayer to play when the screen is turned off?

Is there any way for me to detect that the screen is turned off?

Upvotes: 2

Views: 960

Answers (2)

Ryan
Ryan

Reputation: 16636

@zoul is correct that using the default audio session category will result in sound form your app being disabled when the user locks the screen. See the Audio Session Programming Guide for direction on which audio session category you should choose.

However, even once your audio session category is set correctly, you'll have another issue to tackle. When the screen is switched off, your application gets suspended per Apple's documentation here: Executing Code in the Background. This means that when the user locks their phone or switches to a different app, your app will stop running and stay in a freeze-dried (task-suspended) state until the user activates your app again. At that point, your app resumes execution as if nothing happened. That's why it appears that your app has continued to function when you unlock the screen.

For alarm behavior, you'll probably want to schedule the delivery of a local notification. A local notification will ensure that the system provides your alert to the user at the time you request, and allows the user to activate your app. See Scheduling the Delivery of Local Notifications for details on how to accomplish this.

Upvotes: 3

zoul
zoul

Reputation: 104065

Maybe you have the wrong audio category? See the documentation for AVAudioSession, especially the audio category settings.

Upvotes: 0

Related Questions