Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AVAudioPlayer stops playing the audio when iPhone goes to sleep

Tags:

iphone

I need to play a background sound all the time as long as my application is running. I tried to use AVAudioPlayer for this purpose. However, it stops playing the sound as soon as the iPhone goes to sleep mode.

Could you let me know how can I fix this problem?

Thanks

like image 688
ebaccount Avatar asked Dec 29 '22 23:12

ebaccount


2 Answers

You may need to set an audio session category. From the "iPhone Application Programming Guide"

A category is a key that identifies a set of audio behaviors for your application. By setting a category, you indicate your audio intentions to iPhone OS, such as whether your audio should continue when the screen locks.

The details about each category are listed at "Audio Session Categories"

like image 116
allenporter Avatar answered May 19 '23 19:05

allenporter


In your particular example you may try the following. It should work right out of the box.

// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];    
// Allow the app sound to continue to play when the screen is locked.
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
like image 31
leviathan Avatar answered May 19 '23 19:05

leviathan