播放的音频文件的顺序背景

问题描述:

在我的应用程序,我有AVAudioPlayer,可以播放MP3的序列,通过initWithData切换到下一个实例:播放的音频文件的顺序背景

我希望让用户继续收听即使他关闭了屏幕或转到了背景,也可以给玩家。我知道,当用户点击它时,我可以使用remotecontrolevents切换到其他音频,但是我可以使其自动切换,就像在iPod播放器中一样?

+0

你的意思后,当前曲目结束? – sooper 2012-04-15 13:18:11

+0

是的,我将url存储到核心数据对象中的音频文件 – 2012-04-15 14:11:02

您需要使用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