我有一系列音频文件,我想按顺序播放。我设置了audioPlayerDidFinishPlaying委托方法来启动序列中的下一个文件。如果我关闭屏幕锁定或者我在模拟器或iOS4设备上运行它,这没有问题。但是,当我在断开连接的设备上运行它时,iOS5,屏幕锁定,它在第一首曲目后停止。屏幕锁定开启后,有没有办法启动新的音轨?
这是我的基本代码
// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];
// Use this code instead to allow the app sound to continue to play when the screen is locked.
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 0;
AudioSessionSetProperty ( kAudioSessionProperty_OverrideCategoryMixWithOthers,
sizeof (doSetProperty),
&doSetProperty
);
// Registers the audio route change listener callback function
AudioSessionAddPropertyListener (
kAudioSessionProperty_AudioRouteChange,
audioRouteChangeListenerCallback,
self
);
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
NSString *path = [[NSBundle mainBundle] pathForResource:filename ofType:@"m4a"];
float vol = [appSoundPlayer volume];
AVAudioPlayer * newAudio=[[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:NULL];
self.appSoundPlayer = newAudio; // automatically retain audio and dealloc old file if new file is loaded
[newAudio release]; // release the audio safely
appSoundPlayer.delegate = self;
[appSoundPlayer prepareToPlay];
[appSoundPlayer setNumberOfLoops:0];
[appSoundPlayer play];
[appSoundPlayer setVolume:vol];
[progTime setProgress:0];
}
- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) lappSoundPlayer successfully: (BOOL) flag {
//... code here to select nex sound track
[lappSoundPlayer play];
}
我已经做到了,所以即使屏幕锁定开启,应用程序仍继续播放当前曲目,我无法让它启动下一曲目。
注意:我已经确认这适用于iOS4。
答案 0 :(得分:2)
您是否设置了音频会话类别,具体为AVAudioSessionCategoryPlayback
,如here所述?
[[AVAudioSession sharedInstance] setDelegate: self];
NSError *error = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
如果这不起作用,根据Apple开发论坛this message中的用户ascanio,尝试另一件事就是将你的应用设置为监听远程控制事件:
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];