天天看點

如何在背景播放音樂

在app plist中增加

<key>UIBackgroundModes</key>

<array>

<string>audio</string>

<string>voip</string>

<string>location</string>

</array>

在函數- (void)applicationDidEnterBackground:(UIApplication *)application 中增加:

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 40000

UIDevice* device = [UIDevice currentDevice];

BOOL backgroundSupported = NO;

if ([device respondsToSelector:@selector(isMultitaskingSupported)])

backgroundSupported = device.multitaskingSupported;

UIApplication* app = [UIApplication sharedApplication];

UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{}];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

// Do the work associated with the task.

[self playerAudio];

});

[app endBackgroundTask:bgTask];

#endif 

播放代碼:

#include <AudioToolbox/AudioToolbox.h>

#include <AVFoundation/AVFoundation.h>

-(void)playerAudio

{

AVAudioSession *audioSession;

audioSession = [AVAudioSession sharedInstance];

[audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];

[audioSession setActive:YES error:nil];

AVAudioPlayer *player;

NSString *path;

NSError * error;

// 設定音樂檔案路徑

path = [[NSBundle mainBundle] pathForResource:@"alarm_clock_30" ofType:@"caf"];

// 判斷是否可以通路這個檔案

if (![[NSFileManager defaultManager] fileExistsAtPath:path])

{

NSLog(@"file not exist!");

return;

}

// 設定 player

player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path] error:&error];

[player setDelegate:self];

self.mPlayer = player;

// 調節音量 (範圍從0到1)

player.volume = 0.4f;

// 準備buffer,減少播放延時的時間

[player prepareToPlay];

// 設定播放次數,0為播放一次,負數為循環播放

[player setNumberOfLoops:10];

NSLog(@"start play!");

[player play];

[player release];

NSLog(@"start playing...");

當你需要播放其他歌曲的時候應該加上

// Handle Audio Remote Control events (only available under iOS 4

if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){

[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

}

- (void)remoteControlReceivedWithEvent:(UIEvent *)event

{

//NSLog(@"UIEventTypeRemoteControl: %d - %d", event.type, event.subtype);

if (event.subtype == UIEventSubtypeRemoteControlTogglePlayPause) {

//NSLog(@"UIEventSubtypeRemoteControlTogglePlayPause");

[self playOrStop:nil];

}

if (event.subtype == UIEventSubtypeRemoteControlPlay) {

//NSLog(@"UIEventSubtypeRemoteControlPlay");

[self playOrStop:nil];

}

if (event.subtype == UIEventSubtypeRemoteControlPause) {

//NSLog(@"UIEventSubtypeRemoteControlPause");

[self playOrStop:nil];

}

if (event.subtype == UIEventSubtypeRemoteControlStop) {

//NSLog(@"UIEventSubtypeRemoteControlStop");

[self playOrStop:nil];

}

if (event.subtype == UIEventSubtypeRemoteControlNextTrack) {

//NSLog(@"UIEventSubtypeRemoteControlNextTrack");

[self fastForward];

}

if (event.subtype == UIEventSubtypeRemoteControlPreviousTrack) {

//NSLog(@"UIEventSubtypeRemoteControlPreviousTrack");

[self rewind];

}

}

官方文檔:

http://developer.apple.com/library/ios/#documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html