Iphone AVAudioPlayer当前正在播放声音并从头开始播放

Iphone AVAudioPlayer当前正在播放声音并从头开始播放,iphone,audio,core-audio,avaudioplayer,Iphone,Audio,Core Audio,Avaudioplayer,我在使用AVAudioPlayer时遇到了一个问题,我想重置一个当前正在播放的播放器,然后让它重新播放 我尝试了以下方法,但运气不佳: 声音播放一次,但当我第二次选择按钮时,它停止了声音,第三次再次启动声音 //Stop the player and restart it if (player.playing) { NSLog(@"Reset sound: %@", selectedSound); [player stop]; [player play]; } else

我在使用AVAudioPlayer时遇到了一个问题,我想重置一个当前正在播放的播放器,然后让它重新播放

我尝试了以下方法,但运气不佳:

声音播放一次,但当我第二次选择按钮时,它停止了声音,第三次再次启动声音

//Stop the player and restart it
if (player.playing) {
    NSLog(@"Reset sound: %@", selectedSound);
    [player stop];
    [player play];
} else {
    NSLog(@"playSound: %@", selectedSound);
    [player play];      
}
我还尝试过使用player.currentTime=0,这表示将重置播放器,但无效。我还尝试重置currentTime=0,然后调用无效的play

//Stop the player and restart it
if (player.playing) {
    NSLog(@"Reset sound: %@", selectedSound);
    player.currentTime = 0;
    [player play];
} else {
    NSLog(@"playSound: %@", selectedSound);
    [player play];      
}

对于您的情况,我将尝试以下方法

//Pause the player and restart it
if (player.playing) {
    NSLog(@"Reset sound: %@", selectedSound);
    [player pause];
}

player.currentTime = 0;
[player play];
如果您要立即再次播放该声音,我建议暂停而不是停止。调用stop“停止播放并撤消播放所需的设置。”

示例:

player.currentTime = 0.0;

如前所述,如果希望声音再次播放,应避免禁用AVAudioPlayer实例并停止播放,而只需重新设置播放位置即可。所以,不要使用stop()或pause(),但如Plumenator所述,只需发出.currentTime=0即可。因此,在您的情况下,您只需执行以下操作:

if (player.isPlaying) { 
   player.currentTime = 0
} else {
   player.play()
}

FWIW,我已经看到将currentTime设置为零就足够了。使用这里描述的方法,我看到音频在快速连续播放了几次后拒绝播放。由于您基本上重复了Plenumerator的评论,您能否通过添加参考代码示例来扩展您的答案?谢谢,这是一个很好的建议。我添加了块,以便更清楚Plumenator的建议:-)谢谢