0

i need to play a simple sound using AVAudioPlayer when screen is locked .How can I do that please help

Shekhar Gupta
  • 6,206
  • 3
  • 30
  • 50
mobile.jugnu
  • 619
  • 2
  • 11
  • 21

2 Answers2

0

First: Add following frameworks into your project

AudioToolbox, CoreAudio, MediaPlayer AVFoundation.

enter image description here Second: Add your info.plist file a new key

Required background modes = App plays audio

enter image description here

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**];
bpolat
  • 3,879
  • 20
  • 26
0

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");
}
Community
  • 1
  • 1
Mihai Fratu
  • 7,579
  • 2
  • 37
  • 63