Swift AVAudioPlayer从Beginning重启

时间:2016-01-28 23:00:12

标签: ios swift avaudioplayer

我有一个AVAudioPlayer存储在名为"播放器"的属性中。当用户单击按钮时,它会触发此代码:

@IBAction func restartPressed(sender: AnyObject) {
    player.play()
}

当用户非常快速地连续两次单击该按钮时,就会出现问题。

如果第一次点击的声音仍在播放,则似乎忽略了第二次通话。

相反,我想要:

a) 第二次点击按钮时,从头开始重启播放器;或

b) 有两个"实例"声音同时播放。

我将如何实现其中一个或两个选项?

2 个答案:

答案 0 :(得分:6)

回答"" 部分(而不是"两者" )这些选项:(a) 如何从头开始停止播放声音:

@IBAction func restartPressed(sender: AnyObject) {
    if player.playing {
        player.pause()
    }
    player.currentTime = 0
    player.play()
}

关于(b):来自Language Ref for AVAudioPlayer

  

使用音频播放器,您可以:

     

...

     
      
  • 同时播放多个声音,每个音频播放器一个声音,精确同步。
  •   

因此,即使两个玩家使用相同的声音,您也需要两个独立的播放器同时(不同步)播放两个独立的声音。我坚持使用(a)

答案 1 :(得分:0)

dfri 的答案已更新为 Swift 4

@IBAction func restartPressed(sender: UIButton) {

    if negativePlayer.isPlaying
    {
        negativePlayer.pause()
    }

    negativePlayer.currentTime = 0
    negativePlayer.play()
}