Sunay
Sunay

Reputation: 417

Swift function playAtTime() Does Not Add Delay

I'm trying to play two audioPlayers, one after the other has finished playing. I'm using the Swift function playAtTime() to create a delay for the second, as follows:

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)

However, no delay occurs. What is my issue here?

Upvotes: 0

Views: 271

Answers (2)

Sunay
Sunay

Reputation: 417

I haven't tried Michael's answer yet, but for those of you wondering how to do it with playAtTime, check out this: http://sandmemory.blogspot.com/2014/12/how-would-you-add-reverbecho-to-audio.html and look at the playEcho function.

The code, for me, looks like this:

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

Upvotes: -1

Michael
Michael

Reputation: 9044

The playAtTime function does not start the play at a given time. Instead it plays immediately, from the given time in the sound to be played. So if you give it 0.6, it will start playing straight away, but the sound will start from 0.6 seconds in. See the documentation here.

If you want to wait before playing, you could use 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()
}

Upvotes: 3

Related Questions