我在使用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];
}
答案 0 :(得分:36)
根据您的情况,我会尝试以下
//Pause the player and restart it
if (player.playing) {
NSLog(@"Reset sound: %@", selectedSound);
[player pause];
}
player.currentTime = 0;
[player play];
如果你要立即再次播放声音,我会建议暂停而不是停止。呼叫停止“停止播放并取消播放所需的设置。”
答案 1 :(得分:1)
Swift示例:
player.currentTime = 0.0;
答案 2 :(得分:1)
如前所述,如果您想再次播放声音,则应避免通过停止禁用AVAudioPlayer实例,而只需要重置其播放位置即可。因此,不要使用stop()或pause(),而是如Plumenator所述,只需发出.currentTime = 0。因此,就您而言,您只需执行以下操作:
if (player.isPlaying) {
player.currentTime = 0
} else {
player.play()
}