I would like to activate a function after a sound is played and complete. I assume that NSTimer needs to be included, but I am not sure of how to implement in order to make it. It is helpful if you could give me some code that works.
1 Answer
You should post code that you tried, and then someone then can help you make the code work. In this case, you don't need a timer for what you're doing. The AVAudioPlayerDelegate protocol on the player was designed for what you are trying to do:
import UIKit import AVFoundation class ViewController: UIViewController, AVAudioPlayerDelegate { var audioPlayer:AVAudioPlayer? func playSound(fileName:NSString) { let path = NSBundle.mainBundle().pathForResource(fileName, ofType:"wav") let url = NSURL.fileURLWithPath(path!) do { try audioPlayer = AVAudioPlayer(contentsOfURL: url) audioPlayer?.delegate = self audioPlayer?.play() } catch { print("Player not available") } } //MARK : AVAudioPlayerDelegate func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool) { print("finished playing, do something else here") } } 1 Comment
Duncan C
This is what I would recommend as well. The
AVAudioPlayerDelegate audioPlayerDidFinishPlaying(_, successfully:) method is how you should invoke code when a sound finishes playing.
swift nstimerfor example gives plenty of results.