2012-04-15 56 views
0

在我的應用程序,我有AVAudioPlayer,可以播放MP3的序列,通過initWithData切換到下一個實例:播放的音頻文件的順序背景

我希望讓用戶繼續收聽即使他關閉了屏幕或轉到了背景,也可以給玩家。我知道,當用戶點擊它時,我可以使用remotecontrolevents切換到其他音頻,但是我可以使其自動切換,就像在iPod播放器中一樣?

+0

你的意思後,當前曲目結束? – sooper 2012-04-15 13:18:11

+0

是的,我將url存儲到核心數據對象中的音頻文件 – 2012-04-15 14:11:02

回答

4

您需要使用AVAudioPlayerDelegate協議。首先它包含在你的界面:

@interface MyAppViewController : UIViewController <AVAudioPlayerDelegate> { 
    AVAudioPlayer *yourPlayer; 
} 

@property (nonatomic, retain) AVAudioPlayer *yourPlayer; 
在您的實現

然後:

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag 
{ 
//This method is called once the file has finished playing 
//Insert code here to play the next file 
} 

不要忘記的yourPlayerdelegate設置爲selfviewDidLoad方法(或任何你決定要放在哪裏它):

- (void)viewDidLoad { 
    [super viewDidLoad] 

    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil]; 
    [[AVAudioSession sharedInstance] setActive: YES error: nil]; 

    if ([[UIApplication sharedApplication] respondsToSelector:@selector(beginReceivingRemoteControlEvents)]){ 
     [[UIApplication sharedApplication] beginReceivingRemoteControlEvents]; 
     [self becomeFirstResponder]; 
    } 

    self.yourPlayer = [[AVAudioPlayer alloc] init]; 
    self.yourPlayer.delegate = self; 
} 

您還需要改變所需的背景模式的info.plist應用程序播放音頻

不要忘記註銷遙控事件(viewDidUnload):

[[UIApplication sharedApplication] endReceivingRemoteControlEvents] 
+0

您確定,如果我在後臺並且我可以訪問managedobjects,那麼將調用** didFinishPlaying **? – 2012-04-15 14:13:16

+0

'audioPlayerDidFinishPlaying'將在後臺調用,您可以在.plist文件中設置上述模式,並調用'beginReceivingRemoteControlEvents'(注意,有些可能會將音頻會話初始化和遠程控制事件放在'viewDidAppear'中)。有一個線程[這裏](http://stackoverflow.com/questions/3185621/is-it-possible-to-test-ios4-multitasking-background-music-playing-on-the-simulat/3243857#3243857)與更多信息。 – sooper 2012-04-15 14:21:56

+0

在模擬器上運行良好,但真正在真實設備上工作 - 你不知道爲什麼它可能會是這樣嗎? – 2012-04-15 15:21:41