Swift函数playAtTime()不添加延迟

时间:2016-02-08 02:46:57

标签: swift audio avaudioplayer

我正在尝试播放两个audioPlayers,一个接一个播放完毕。我正在使用Swift函数playAtTime()为第二个创建延迟,如下所示:

var audioPlayer1 = AVAudioPlayer()
var audioPlayer2 = AVAudioPlayer()

let soundPathA = NSBundle.mainBundle().pathForResource("A", ofType: "m4a")
let soundURLA = NSURL.fileURLWithPath(soundPathA!)

let soundPathB = NSBundle.mainBundle().pathForResource("B", ofType: "m4a")
let soundURLB = NSURL.fileURLWithPath(soundPathB!)

var noteA = Sound()
noteA.URL = soundURLA

var noteB = Sound()
noteB.URL = soundURLB

self.audioPlayer1 = try!AVAudioPlayer(contentsOfURL: soundURLA)
self.audioPlayer2 = try!AVAudioPlayer(contentsOfURL: soundURLB)

let duration : NSTimeInterval = audioPlayer1.duration
self.audioPlayer1.play()
self.audioPlayer2.playAtTime(duration)

然而,没有延迟发生。我的问题在这里是什么?

2 个答案:

答案 0 :(得分:3)

playAtTime功能无法在给定时间开始播放。相反,它会在播放声音的给定时间内立即播放。因此,如果你给它0.6,它将立即开始播放,但声音将从0.6秒开始。请参阅文档here

如果您想在播放前等待,可以使用dispatch_after

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.6 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    self.audioPlayer2.play()
}

答案 1 :(得分:-1)

我还没有尝试过迈克尔的答案,但对于那些想知道如何使用playAtTime进行操作的人,请查看:http://sandmemory.blogspot.com/2014/12/how-would-you-add-reverbecho-to-audio.html并查看playEcho函数

对我而言,代码如下所示:

var playTime1 : NSTimeInterval = audioPlayer2.deviceCurrentTime + (duration1*Double(value))
self.audioPlayer1.stop()
self.audioPlayer1.currentTime = 0
self.audioPlayer1.play()