2013-04-16 104 views
0

我有一台播放音乐的AVAudioPlayer,并在当前播放完成后自动播放下一首歌曲。当应用程序处于打开状态时,此功能完美无缺,但当应用程序未打开时,它只会播放下一首歌曲。播放一首歌曲开始到结束,而在后台,AVAudioPlayer仅在背景中播放1首歌曲

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

不会再次调用之后。我有:

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

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

回答

0

您是否检查过支持文件 - > YourProject-Info.plist - >Required background modes, 和App plays audio那个Key?必须添加到plist才能在后台播放音乐。

+0

是的,我确实在我的plist中有。我刚刚得到它的工作,出于某种原因,将AVAudioPlayers委托设置为当前视图使它可以工作,即使我在每首新歌曲中重复使用同一个音频播放器。 – user2272641

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]; 
} 

----- //老办法// -----

如果还有人在那里仍然在努力解决这个问题,我发现这是最好的解决办法。

- (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 

} 
相关问题