屏幕锁定时如何使用AVAudioPlayer播放音乐 [英] how to play music using AVAudioPlayer when screen os locked

查看:100
本文介绍了屏幕锁定时如何使用AVAudioPlayer播放音乐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

锁定屏幕后,我需要使用AVAudioPlayer播放简单的声音.我该怎么办

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

推荐答案

首先:在您的项目中添加以下框架

First: Add following frameworks into your project

AudioToolbox, CoreAudio, 媒体播放器 AVFoundation.

AudioToolbox, CoreAudio, MediaPlayer AVFoundation.

第二:将您的info.plist文件添加为新密钥

Second: Add your info.plist file a new key

所需的背景模式=应用播放音频

Required background modes = App plays audio

第三步:创建一个名为keepAwakeForAudio的方法,并在播放音频后立即调用它

Third: Create a method called keepAwakeForAudio and call it just after playing your audio

-(void)keepAwakeForAudio

-(void)keepAwakeForAudio

{ UInt32 sessionCategory = kAudioSessionCategory_MediaPlayback; AudioSessionSetProperty(kAudioSessionProperty_AudioCategory,sizeof(sessionCategory),& sessionCategory); AudioSessionSetActive(true); }

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

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

这篇关于屏幕锁定时如何使用AVAudioPlayer播放音乐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆