Good. This is a background sound solution on iOS4 and iOS5 (it definitely works before iOS 5.0.1), and I tested it only with AVPlayer. It should probably work for MPMusicPlayerController as well.
Necessary framework:
AVFoundation.frameworkAudioToolbox.framework
In Info.plistfor the key UIBackgroundModesadd audio.
In MyAppDelegate.h:
- reference
<AVFoundation/AVFoundation.h>and<AudioToolbox/AudioToolbox.h> implement protocol AVAudioSessionDelegate:
@interface MyAppDelegate : NSObject <UIApplicationDelegate, AVAudioSessionDelegate>
define method ensureAudio:
- (BOOL) ensureAudio;
In MyAppDelegate.m:
implement the method ensureAudio:
- (BOOL) ensureAudio
{
[[AVAudioSession sharedInstance] setDelegate: self];
NSError *categoryError = nil;
if (![[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&categoryError]) {
NSLog(@"Audio session category could not be set");
return NO;
}
NSError *activationError = nil;
if (![[AVAudioSession sharedInstance] setActive: YES error: &activationError]) {
NSLog(@"Audio session could not be activated");
return NO;
}
UInt32 doChangeDefaultRoute = 1;
AudioSessionSetProperty(kAudioSessionProperty_OverrideCategoryMixWithOthers, sizeof(doChangeDefaultRoute), &doChangeDefaultRoute);
return YES;
}
application:didFinishLaunchingWithOptions:, , [self ensureAudio]:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self ensureAudio];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
return YES;
}
AVAudioSessionDelegate :
#pragma mark - AVAudioSessionDelegate
- (void) beginInterruption
{
}
- (void) endInterruption
{
[self ensureAudio];
}
- (void) inputIsAvailableChanged:(BOOL)isInputAvailable
{
}
, . ol '[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler], , , .
( , ARC, release):
NSURL * file = [[NSBundle mainBundle] URLForResource:@"beep" withExtension:@"aif"];
AVURLAsset * asset = [[AVURLAsset alloc] initWithURL:file options:nil];
AVPlayerItem * item = [[AVPlayerItem alloc] initWithAsset:asset];
__block AVPlayer * player = [[AVPlayer alloc]initWithPlayerItem:item];
__block id finishObserver = [[NSNotificationCenter defaultCenter] addObserverForName:AVPlayerItemDidPlayToEndTimeNotification
object:player.currentItem
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification *note) {
[[NSNotificationCenter defaultCenter] removeObserver:finishObserver];
player = nil;
}];
[asset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:@"tracks"] completionHandler:^{
[player play];
}];
shoooooooooooooo !