其實在網絡上很多,都是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];
提示記得喂狗 否則只能播放一陣子。。。