AvAudioPlayer音频的后台播放
其实在网络上很多,都是N年前的方式,搜索一下全部都出来了。做一个demo演示一下。但是发现有许多的问题,找了许久,才发现又是xcode的一个bug,不管是什么资源文件只要是修改不删除现有的编译项目,xcode是不会下载到手机里。
要先在退出后播放,那必须要设置一下Info.plist.添加一行 Required background modes,在其下加入app plays audio 如下图,这个意思就是说,你要后台播放一个音频。
(建议清除一下原先编译项目,否则你总是惆怅啊!惆怅!)
引入AVFoundation framework动态库,通过以下代码注册后台播放:
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setActive:YES error:nil];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
原理:通知OS该app支持background audio。缺省情况下,当按下home键时,当前正在运行的程序被suspend,状态从active变成in-active,也就是说如果正在播放音频,按下HOME后就会停止。这里需要让app在按在HOME后,转到后台运行而非被suspend。
完整的代码,添加一个1223.mp3资源,把下面这段代码贴到可以运行的地方,运行---听到声音后按以下home键试试,按两下你就会发现在播放声音控制面板中变成你的图标。
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
if (activationError) {
NSLog(@"activ error");
}
NSString *soundFilePath = [[NSBundlemainBundle] pathForResource:@"1223" ofType:@"mp3"];
NSURL *url = [NSURL URLWithString:soundFilePath];
//alloc a new player
audioPlayer = [[AVAudioPlayeralloc] initWithContentsOfURL:url error:nil];
if (!audioPlayer) {
NSLog(@"error");
}
//prepare and set delegate
[audioPlayer prepareToPlay];
[audioPlayer setDelegate:self];
//play audio
[audioPlayer play];
提示记得喂狗 否则只能播放一阵子。。。