当点击按钮时重复播放声音

3

我正在尝试为我的应用添加声音。当我点击按钮时,我希望它能播放一个快速的声音。但是,当我快速重复地点击按钮时,声音就无法正常工作(当我点击按钮5或6次时,它只会播放1或2次)。这是我的按钮代码:

player.play()

我有这个外部

var player = AVAudioPlayer()
let audioPath = NSBundle.mainBundle().pathForResource("illuminati", ofType: "wav")

Viewdidload:

do {
        try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
    } catch {}

如何更好地重复播放声音?谢谢。

2个回答

2
你的声音只播放几次的原因是,即使您连续多次按下按钮,歌曲会一直播放直到结束或者你停止它。你可以手动停止音乐,所以在按下播放声音的按钮之前,你可以说停止音乐。
player.stop() 

然后

player.play()

这有帮助吗?

2
问题在于您在前一次调用完成之前多次调用了play。 您需要跟踪用户点击按钮的次数,并依次播放歌曲。
您可以这样做:
  1. Use an integer in you class to keep track of number of times that the button is clicked

    var numClicks = 0
    var buttonClickTime:NSDate? = nil // The last time when the button is clicked
    
    @IBAction func yourbuttonclickfunction() {
        numClicks++; 
        buttonClickTime = NSDate()
        player.play()
    } 
    
  2. Register the delegate of AVAudioPlayerDelegate

    do {
          try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
    
          // Add this 
          player.delegate = self
    } catch {}
    
  3. In the delegate function, play the song again when the previous one reach the end:

    optional func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer,
                         successfully flag: Bool)
    {
         if --numClicks > 0
         {
             let now = NSDate()
             let duration = now.timeIntervalSinceDate(buttonClickTime!)
    
             // If the button click was less than 0.5 seconds before
             if duration < 0.5 
             {
                 // Play the song again
                 player.play();
             } 
         }
    }
    

所以代码运行良好。但是,当我反复点击按钮时,它会播放那么多次声音。如果停止轻敲,声音仍然在播放。我该如何解决这个问题?在“player.play()”之前加上“player.stop()”似乎没有效果... - Pranav Wadhwa
@penatheboss,你好。我有点困惑。您希望玩家听到声音播放的次数与他点击按钮的次数相同。这不是您想要的吗?如果在用户没有点击按钮时停止播放,则无法获得您期望的播放次数。 - Yuchen
我希望它能像这样。 - Pranav Wadhwa
@penatheboss,那么想法是如果用户停止点击0.5秒钟,就停止播放。请参考我的答案修改。看起来这就是你要的。 - Yuchen
我尝试使用我通常的代码(声明音频路径和播放器,然后设置播放器,然后播放播放器)。但是,它没有起作用。我将代码放在按钮中。你知道为什么吗? - Pranav Wadhwa
显示剩余5条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接