iOS 在后台播放音频
在属性列表(.plist)文件中添加一个名为Requiredbackgroundmodes的键。
然后添加以下代码
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);
IfyouwantchangesaspereventsyouhavetoaddfollowingcodeinAppDelegate.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;
}
}
}在通知的基础上,必须对它进行改进。