我在项目中使用AVAudioPlayer实例按顺序播放背景音乐剪辑和语音音频剪辑。我必须将音频与显示的动画同步。除了在诸如呼叫之类的中断之后的场景(即)之外,它工作得很好。如果中断开始,动画将暂停,如果结束,它将恢复,音频应该以相同的方式,以便它可以完美同步。
我使用过AVAudioPlayer的委托方法,在中断时调用
- (void) audioPlayerBeginInterruption: (AVAudioPlayer *) player {
[self pauseAllPlayers];
}
- (void) audioPlayerEndInterruption: (AVAudioPlayer *) player withOptions:(NSUInteger) flags{
[self playAllPlayers];
}
-(void)pauseAllPlayers
{
if(musicPlayer1)
[musicPlayer1 pause];
if(musicPlayer2)
[musicPlayer2 pause];
// ... paused all players the similar way
}
-(void)playAllPlayers
{
if(musicPlayer1)
[musicPlayer1 play];
// .. played all players the similar way
}
我还设置了委托给自己。它工作正常,但音频剪辑在中断后没有从相同的状态恢复,它从头开始播放剪辑。我也尝试了以下内容:
1)
- (void)endInterruptionWithFlags:(NSUInteger)flags {
if (flags) {
if (AVAudioSessionInterruptionFlags_ShouldResume) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1), dispatch_get_main_queue(), ^{
[self playAllPlayers];
});
}
}
}
2)
- (void) audioPlayerEndInterruption: (AVAudioPlayer *) player withOptions:(NSUInteger) flags{
[NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(resumeBG) userInfo:nil repeats:NO];
[musicPlayer1 play];
}
-(void) resumeBG
{
[musicPlayer2 play]; // This is the player that plays background music.
}
3)
- (void) audioPlayerBeginInterruption: (AVAudioPlayer *) player {
[self stopAllAudioPlayers];
}
- (void) audioPlayerEndInterruption: (AVAudioPlayer *) player withOptions:(NSUInteger) flags{
[self playAllPlayers];
}
-(void) stopAllAudioPlayers
{
if(musicPlayer1)
[musicPlayer1 stop];
if(musicPlayer2)
[musicPlayer2 stop];
//...
}
但这些都行不通。我需要在中断开始时从同一状态恢复BG和语音音频片段。 AVAudioPlayer本身有办法吗?
编辑:
根据Duncan C的回答,我尝试了以下内容:
- (void) audioPlayerBeginInterruption: (AVAudioPlayer *) player {
[self storeTime];
}
- (void) audioPlayerEndInterruption: (AVAudioPlayer *) player withOptions:(NSUInteger) flags{
[self resumeAtTime];
}
- (void) storeTime
{
player1Time = [player1 currentTime];
player2Time = [player2 currentTime];
}
-(void) resumeAtTime
{
[player1 playAtTime:player1Time];
[player2 playAtTime:player2Time];
}
我还尝试在(player1.deviceCurrentTime + player1Time)
函数中使用resumeAtTime
。这是正确的方法吗?我也尝试过使用player.currentTime/player1.rate
答案 0 :(得分:1)
如果播放方法从开头播放声音或在暂停后继续播放,则文档不会清楚说明。它只是说它播放声音,从一开始就强烈建议播放。你的发现表明这就是它的作用。
这是我要做的。在暂停之前,使用currentTime方法获取声音的播放点。
然后使用playAtTime在停止播放时恢复每个声音。