AVAudioPlayer will not play when device is locked

本小妞迷上赌 提交于 2019-12-08 04:26:33

问题


I am using AVAudioPlayer in my application. When I select a song it plays, but my problem is, it is not playing when the device gets locked.


回答1:


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.




回答2:


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];



回答3:


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 ?



来源:https://stackoverflow.com/questions/6516954/avaudioplayer-will-not-play-when-device-is-locked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!