i need to play a simple sound using AVAudioPlayer when screen is locked .How can I do that please help
问题:
回答1:
This was answered here before. As the thing suggests you need to set your audio session as in this example
UInt32 category = kAudioSessionCategory_MediaPlayback;
OSStatus result = AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,
sizeof(category), &category);
if (result){
DebugLog(@"ERROR SETTING AUDIO CATEGORY!\n");
}
result = AudioSessionSetActive(true);
if (result) {
DebugLog(@"ERROR SETTING AUDIO SESSION ACTIVE!\n");
}
回答2:
First: Add following frameworks into your project
AudioToolbox, CoreAudio, MediaPlayer AVFoundation.
Second: Add your info.plist file a new key
Required background modes = App plays audio
Third: Create a method called keepAwakeForAudio and call it just after playing your audio
-(void)keepAwakeForAudio
{ UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback; AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (sessionCategory), &sessionCategory); AudioSessionSetActive(true); }
//////
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/rain1_Rain_on_Street.m4a", [[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;
if (audioPlayer == nil)
NSLog([error description]);
else
[audioPlayer play];
[self **keepAwakeForAudio**];