
Adding Basic Audio with variable delayed play to your app
First you need to find the audio file you want to use and then add it to your project. Then:
This is the basic function. If you have any questions let me know.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
// import this at the app beginning to be able to play Audio import AVFoundation</code> class ViewController: UIViewController { // declare the path to the audio file and the audio Player var boing = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("bong", ofType: "wav")!) var audioPlayer = AVAudioPlayer() override func viewDidLoad() { super.viewDidLoad() // Delay Function == Pretty Cool :) func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), closure) } //Audio Function with the delay built in func playAudio (time: Double) { delay(time) { self.audioPlayer = AVAudioPlayer(contentsOfURL: self.boing, error: nil) // point to the audio file self.audioPlayer.prepareToPlay() // prepare the Audio Player self.audioPlayer.play() } } // Call the Audio and select the delay ( seconds ) playAudio(0.2) playAudio(1.15) |