我正在尝试为我的应用程序添加声音。我喜欢它,因为当我点击一个按钮时,它会播放快速的声音。但是,当快速重复点击按钮时,声音效果不佳(当我点击按钮 5 或 6 次时,它只播放 1 或 2 次)。这是我在按钮中的代码
player.play()
我在外面有这个
var player = AVAudioPlayer()
let audioPath = NSBundle.mainBundle().pathForResource("illuminati", ofType: "wav")
查看加载:
do {
try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!))
} catch {}
如何更好地反复播放声音?谢谢。
最佳答案
问题是您在上一个调用完成之前多次调用 play
。您需要跟踪用户单击按钮的次数和播放歌曲的次数。
这是你可以做的:
在你的类中使用一个整数来跟踪按钮被点击的次数
var numClicks = 0 var buttonClickTime:NSDate? = nil // The last time when the button is clicked @IBAction func yourbuttonclickfunction() { numClicks++; buttonClickTime = NSDate() player.play() }
注册
AVAudioPlayerDelegate
的委托(delegate)do { try player = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: audioPath!)) // Add this player.delegate = self } catch {}
在delegate函数中,当上一首歌曲播放结束时再次播放:
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(); } } }
关于ios - 点击按钮时重复播放声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34020266/