Swift – 有一个audio重复,但它会间隔?

Swift中 ,我播放了一首歌,它在viewDidLoad中播放。 它长16秒,全部播放16秒。 我希望它永远重复。 我做了一个NSTimer ,每16秒播放一首歌。 但是,当应用程序加载时,它播放16秒,停止16秒,播放等。

println("just doing some dandy debugging here.") println("just doing some dandy debugging here.") 每16秒打印一次。

这是如何修复的?

码:

  //these var's are created on the top of the file. var soundTimer: NSTimer = NSTimer() var audioPlayer2 = AVAudioPlayer() var soundTwo = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("sound", ofType: "wav")) //this stuff is in the viewDidLoad function. audioPlayer2 = AVAudioPlayer(contentsOfURL: soundTwo, error: nil) audioPlayer2.prepareToPlay() audioPlayer2.play() soundTimer = NSTimer.scheduledTimerWithTimeInterval(16, target: self, selector: Selector("soundTimerPlayed"), userInfo: nil, repeats: true) func soundTimerPlayed() { println("just doing some dandy debugging here.") audioPlayer2.stop() audioPlayer2.prepareToPlay() audioPlayer2.play() } 

相反,只需要简单,正式的做法。 从numberOfLoops属性的文档 :

设置任何负整数值以无限循环声音,直到您调用停止方法。

但是你的实际问题几乎肯定是因为你早点停止播放:

停止方法不会将currentTime属性的值重置为0.换句话说,如果您在播放期间调用停止,然后调用播放,则播放将从停止的位置恢复。

发生什么事情就是在样本的实际结束之前停止声音播放 – 您的计时器被设置为太短的时间。 定时器第一次触发时,“播放”正在播放最后留下的less量安静或无声的声音,然后停止播放。 下一次,由于样本已成功到达播放结束,当前时间已被重置,所以在下一个定时器时间间隔后,又过了16秒,从头开始成功地开始播放。 并重复。

正如杰克在他的评论中所说,这就是为什么有一个委托callback给你一个踢时,实际上已经完成播放,但我仍然只是设置numberOfLoops而不打扰复杂的东西,如果你只需要声音循环无限期。

(如果你非常想重复你的确切的计时器事件,那么只需在再次播放之前将currentTime设置为0)。