开发者

AVAudioPlayer will not play when device is locked

I am using AVAudioPlayer in my application. When I select a song it plays, but my problem is, it is not playin开发者_如何学Gog when the device gets locked.


You need to read Executing Code in the Background in Apple's documentation. If you set the UIBackgroundModes key in you app's Info.plist to audio, audio will keep playing while backgrounded.

See the sections Declaring the Background Tasks You Support and Playing Background Audio in the aforementioned documentation.


All we need to make music play in the background with AVAudioPlayer by two step:

Step 1: Choose Project -> Capabilities -> Enable Background Modes -> Select Audio Mode

Step 2: Use this code:

NSURL *soundURL = [[NSBundle mainBundle] URLForResource:@"demo" withExtension:@"mp3"];
avSound = [[AVAudioPlayer alloc] initWithContentsOfURL:soundURL error:nil];
[avSound setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];
[[AVAudioSession sharedInstance] setActive: YES error: nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[avSound prepareToPlay];
[avSound setNumberOfLoops:-1];
[avSound setVolume:1.0]; 

Note that with this line the music can start even if the app was in the background:

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];


As per my knowledge it is not possible to play sound when device locked. Can't you just disallow device to lock and alive apps active always until user close it manually ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜