简体   繁体   English

如何在iOS Swift中创建延迟,以便任务A在任务B开始之前结束?

[英]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) 开始任务A(播放声音)
  2. wait until task A finish 等到任务A完成
  3. start task B (listen to mic for 4 seconds) 开始任务B(听麦克风4秒钟)
  4. stop task B 停止任务B
  5. repeat 1-4 重复1-4

I use dispatch_after for step 3 and 4 but that didn't work. 我在第3步和第4步中使用了dispatch_after,但这没有用。 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()
        })
    }

}

Since you have already set player.delegate = self , you need to implement the method ( See documentation here ) 由于您已经设置了player.delegate = self ,因此需要实现该方法( 请参见此处的文档

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 然后,您可以使用@John的答案(NSTimer)来完成其余任务

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

使用NSTimer

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM