how to play music using AVAudioPlayer when screen os locked

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 20:11:55

问题


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


来源:https://stackoverflow.com/questions/6706939/how-to-play-music-using-avaudioplayer-when-screen-os-locked

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