0

在我的应用程序中,我有一个AVAudioPlayer实例,它播放一系列 mp3,通过以下方式切换到下一个initWithData

我想让用户即使关闭屏幕或进入后台也能继续收听播放器。我知道,remotecontrolevents当用户点击它时,我可以用来切换到其他音频,但我可以让它自动切换,就像在 iPod 播放器中一样?

4

1 回答 1

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
}

不要忘记在你的方法中设置delegateof yourPlayerto (或者你决定把它放在哪里):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 中的所需背景模式更改为App 播放音频

不要忘记取消注册远程控制事件(viewDidUnload):

[[UIApplication sharedApplication] endReceivingRemoteControlEvents]
于 2012-04-15T13:37:45.303 回答