Swift - 有音频重复,但它间隔播放?

时间:2014-06-27 16:15:05

标签: ios audio swift avaudioplayer

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

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

这是如何解决的?

CODE:

 //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()
}

1 个答案:

答案 0 :(得分:2)

请以简单,官方的方式来做。来自the documentation of the numberOfLoops property

  

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

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

  

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

发生的事情是您在实际结束前稍微停止声音播放 - 您的计时器设置为太短的时间。第一次触发计时器时,"播放"正在播放最后留下的微小的安静或无声的声音,然后停止。下一次,currentTime已被重置,因为样本已成功到达播放结束,因此在 next 计时器间隔后,再过16秒后,从头开始成功播放。并重复一遍。

正如杰克在评论中观察到的那样,这就是为什么当回放实际结束时会有一个代表回调给你踢,但我仍然只是设置numberOfLoops并且不用复杂的东西,如果你只需要声音无限循环。

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