在后台播放音频
在属性列表(.plist)文件中添加名为 Required background modes 的密钥。
如下图
并添加以下代码
AppDelegate.h
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>
AppDelegate.m
在应用程序 didFinishLaunchingWithOptions 中
[[AVAudioSession sharedInstance] setDelegate:self];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
UInt32 size = sizeof(CFStringRef);
CFStringRef route;
AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &size, &route);
NSLog(@"route = %@", route);
如果你希望根据事件进行更改,则必须在 AppDelegate.m 中添加以下代码
- (void)remoteControlReceivedWithEvent:(UIEvent *)theEvent {
if (theEvent.type == UIEventTypeRemoteControl) {
switch(theEvent.subtype) {
case UIEventSubtypeRemoteControlPlay:
[[NSNotificationCenter defaultCenter] postNotificationName:@"TogglePlayPause" object:nil];
break;
case UIEventSubtypeRemoteControlPause:
[[NSNotificationCenter defaultCenter] postNotificationName:@"TogglePlayPause" object:nil];
break;
case UIEventSubtypeRemoteControlStop:
break;
case UIEventSubtypeRemoteControlTogglePlayPause:
[[NSNotificationCenter defaultCenter] postNotificationName:@"TogglePlayPause" object:nil];
break;
default:
return;
}
}
}
基于通知必须工作..