PatJ
PatJ

Reputation: 3

How can I create delay in iOS Swift so task A ends before task B begins?

Basically what I need is followings:

  1. start task A (play sound)
  2. wait until task A finish
  3. start task B (listen to mic for 4 seconds)
  4. stop task B
  5. repeat 1-4

I use dispatch_after for step 3 and 4 but that didn't work. The simulator played all the sound files without listening to the mic. How can I fix this problem?

@IBAction func play(sender: AnyObject) {

    var words = ["laud","puff","keen","death","knock"]
    for item in words {
        let path = NSBundle.mainBundle().pathForResource(item, ofType: "m4a")
        let fileURL = NSURL(fileURLWithPath: path!)

        do {
            player = try AVAudioPlayer(contentsOfURL: fileURL)
            player.delegate = self
            player.play()
        } catch {
            print("Error AVAudioPlayer")
        }

        while player.playing {
            print("Playing")
        }
        print("stop playing")

        startListening()

        let seconds = 4.0
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(seconds * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), { () -> Void in
            self.stopListening()
        })
    }

}

Upvotes: 0

Views: 78

Answers (2)

Christopher
Christopher

Reputation: 731

Since you have already set player.delegate = self, you need to implement the method (See documentation here)

audioPlayerDidFinishPlaying(_:successfully:)

to catch the event that audio playing was finished

func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) {
    if flag {
        startLitening()
    }
}

Then, you can use @John 's answer which is NSTimer to do the remaining tasks

let seconds = 4.0
let timer  = NSTimer.scheduledTimerWithTimeInterval(seconds * Double(NSEC_PER_SEC), target: self, selector: "stopListening:", userInfo: "", repeats: false)

stopListening() {
    // do anything else
    playAudioAgain()
}

Upvotes: 1

John
John

Reputation: 2480

Use a NSTimer:

let timer  = NSTimer.scheduledTimerWithTimeInterval(seconds * Double(NSEC_PER_SEC), target: self, selector: "stopListening:", userInfo: "", repeats: false)

Upvotes: 0

Related Questions