Reputation: 3
Basically what I need is followings:
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
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
Reputation: 2480
Use a NSTimer
:
let timer = NSTimer.scheduledTimerWithTimeInterval(seconds * Double(NSEC_PER_SEC), target: self, selector: "stopListening:", userInfo: "", repeats: false)
Upvotes: 0