18

我在使用 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 然后调用不起作用的播放。

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

3 回答 3

40

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

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

player.currentTime = 0;
[player play];

如果您要立即再次播放声音,我建议您暂停而不是停止。调用 stop “停止播放并撤消播放所需的设置。”

于 2009-07-21T23:39:07.910 回答
3

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

if (player.isPlaying) { 
   player.currentTime = 0
} else {
   player.play()
}
于 2019-06-20T13:46:20.293 回答
2

快速示例:

player.currentTime = 0.0;
于 2016-07-28T01:43:18.400 回答