IOS的後臺模式播放音樂( BackGroundMode)

   IOS4.0以後增加了多任務,在IOS程序退到後臺之後是幾種任務是可以繼續執行的,比如說音樂播放,雜誌下雜,location,廢話不多說,現在我們以後臺音樂播放爲例開始我們的後臺模式。

1.編輯plist,設置我們需要的後臺模式,其次添加我們的音樂文件



從上圖中可以清楚的看到,我添加的音樂文件是hello.mp3,然後我在info.plist中設置的後臺模式有3種,這是爲了讓大家一目瞭然,其實我們只用到第一種,後臺播放音頻文件的設置。

2.在進入到後臺模式的回調函數中調用聲音播放的函數


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    
    NSError *error;
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:&error];
    [session setCategory:AVAudioSessionCategoryPlayback error:&error];
    NSString *filePath    = [[NSBundle mainBundle]pathForResource:@"Hello" ofType:@"mp3"];
    BOOL fileExit = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (fileExit) {
        _player = [[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL URLWithString:filePath ] error:nil ];
        [_player prepareToPlay];
        
    }

    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        self.viewController = [[[com_gamewaveViewController alloc] initWithNibName:@"com_gamewaveViewController_iPhone" bundle:nil] autorelease];
    } else {
        self.viewController = [[[com_gamewaveViewController alloc] initWithNibName:@"com_gamewaveViewController_iPad" bundle:nil] autorelease];
    }
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

上面的代碼中,[session setCategory:AVAudioSessionCategoryPlaybackerror:&error];這一行是表明我要後臺繼續播放這個文件


3,代碼編譯通過,運行,通過!


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章