AVAudioPlayer只在后台播放1首歌曲

时间:2013-04-16 01:48:17

标签: ios avaudioplayer

我有一个播放音乐的AVAudioPlayer,当完成当前音乐时会自动转到下一首歌曲。这在应用程序打开时非常有效,但是当应用程序未打开时,它只会播放下一首歌曲。在后台播放一首歌后开始播放,

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag

不会再被召唤。我有:

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

在viewdidload中,但问题仍然存在,有谁知道会导致什么?

2 个答案:

答案 0 :(得分:0)

您是否检查了支持文件 - > YourProject-Info.plist - > Required background modes, 该密钥中的项目App plays audio?必须将它添加到plist才能在后台播放音乐。

答案 1 :(得分:0)

编辑:这是另一种方式,减少错误:这会每半秒检查一次当前的进度(更短的时间可以更准确地改变歌曲)。只需拨打以下两个选择器中的一个:

- (void)applicationDidEnterBackground:(UIApplication *)application

或者在任何其他方法中,由您决定。

-(void ) sel1 {

[self performSelector:@selector(sel2) withObject:nil afterDelay:0.1];
NSLog(@"%f", ( _audioPlayer.duration -  _audioPlayer.currentTime) );


if (( _audioPlayer.duration - _audioPlayer.currentTime) < 0.5) {

    [self nextSong];
}

}

-(void) sel2 {

 [self performSelector:@selector(sel1) withObject:nil afterDelay:0.4];
}

----- // OLD WAY // -----

如果还有人试图解决这个问题,我发现这是最好的解决方案。

- (void)applicationDidEnterBackground:(UIApplication *)application
{

float remaining = _audioPlayer.duration - _audioPlayer.currentTime;
[self performSelector:@selector(nextSong) withObject:nil afterDelay:remaining];

}

只需在应用进入后台后执行选择器。这将强制AVAudioPlayer在当前声音结束后立即更改歌曲。你必须要小心,因为每次应用程序进入后台时都会设置一个新的选择器,它们会堆叠起来(所以它会同时多次调用选择器)。我用一个计数器解决了这个问题,总是保持在1.这样:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
if (counter == 0) {
float remaining = _audioPlayer.duration - _audioPlayer.currentTime;
[self performSelector:@selector(nextSong) withObject:nil afterDelay:remaining];
counter ++;
}

}


-(void) nextSong {
counter = 0;

//Next Song Method

}