iOS音樂背景播放功能

  • 1
這陣子在處理iOS背景音樂播放的功能,筆記一下


1.在UIViewController裡加上: 
AVAudioSession *session = [AVAudioSession sharedInstance];
[session setCategory:AVAudioSessionCategoryPlayback error:nil];
[session setActive:YES error:nil]; 


2.在 info.plist 中加上「required background modes」Key ,  Value 選 App plays audio

3.若想要在螢幕鎖定或是多工列(按兩下Home)控制聲音播放的話,加上
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 
[self becomeFirstResponder]; 
關閉加上
[[UIApplication sharedApplication] endReceivingRemoteControlEvents]; 
[self resignFirstResponder];
 設定canBecaomFirstResponder為Yes

- (BOOL)canBecomeFirstResponder {
    NSLog(@"canBecomeFirstResponder");    return YES;}


4. 加控制的事件偵測
-(void)remoteControlReceivedWithEvent:(UIEvent *)receivedEvent{
    if (receivedEvent.type == UIEventTypeRemoteControl) {
        switch (receivedEvent.subtype) {
            case UIEventSubtypeRemoteControlTogglePlayPause:                //開始or暫停
                break;
            case UIEventSubtypeRemoteControlPreviousTrack:                //上一首
                break;
            case UIEventSubtypeRemoteControlNextTrack:                //下一頁
                break;
            case UIEventSubtypeRemoteControlBeginSeekingBackward:                //長按後退鍵
                break;
            case UIEventSubtypeRemoteControlEndSeekingBackward:                //長按後退鍵結束
                break;
              //還有其他事件等你自已發掘
            default:
                break;
        }
    }
}

5.可以加上以下這段,改變播放器的曲目資訊與專輯圖片
使用前請先 import MediaPlayer/MediaPlayer.h

- (void)configNowPlayingInfoCenter {
     
    Class playingInfoCenter = NSClassFromString(@"MPNowPlayingInfoCenter");
    if (playingInfoCenter) {
      
        MPNowPlayingInfoCenter *center = [MPNowPlayingInfoCenter defaultCenter];      
        // 當前播放歌曲的圖片        MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:[UIImage imageNamed:@"Album.png"]];      
        NSDictionary*songInfo = [NSDictionary dictionaryWithObjectsAndKeys:@"專輯名稱", MPMediaItemPropertyArtist,                                 @"專輯標題", MPMediaItemPropertyTitle,
                                 artwork, MPMediaItemPropertyArtwork,
                                 @"專輯介紹", MPMediaItemPropertyAlbumTitle,
                                 nil];
        center.nowPlayingInfo = songInfo;
      
    }
}


6.如果在Cocos2d裡想實現以上的功能,若有用到SimpleAudioEngine,請把以下程式碼插在步驟1.的程式碼之前,目的是讓SimpleAudioEngine暫停,不讓音效的資源佔住。
[SimpleAudioEngine end];

以上,就可以很輕鬆的把這個功能加到應用程式裡面了。