需要应用能实现在隐藏后播放音频的效果。在按下home键后也能继续播放。
下面的代码只能在home键按两下后进行一些远程控制,背景中播放音频就不行。,我需要的是在应用隐藏背景模式下播放MP3格式的文件。
在info.plist文件中添加了选项。
需要处于背景模式的应用能播放音频。
- (void) setupAudioSession {
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
// Specify that this object is the delegate of the audio session, so that this object's endInterruption method will be invoked when needed.
[audioSession setDelegate: self];
// Assign the Playback category to the audio session.
NSError *audioSessionError = nil;
//[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[audioSession setCategory: AVAudioSessionCategoryPlayback error: &audioSessionError];
if (audioSessionError != nil) {
NSLog (@"Error setting audio session category.");
return;
}
// Activate the audio session
[audioSession setActive: YES error: &audioSessionError];
if (audioSessionError != nil) {
NSLog (@"Error activating audio session during initial setup.");
return;
}
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
//if it is a remote control event handle it correctly
if (event.type == UIEventTypeRemoteControl) {
if (event.subtype == UIEventSubtypeRemoteControlTogglePlayPause) {
//[player play];
[self playAction];
// } else if (event.subtype == UIEventSubtypeRemoteControlPause) {
// [player pause];
} else if (event.subtype == UIEventSubtypeRemoteControlPreviousTrack) {
[self rewButtonPressed];
} else if (event.subtype == UIEventSubtypeRemoteControlNextTrack)
[self ffwButtonPressed:nil];
}}
请高手指教一些,非常感谢!