3

I am trying to make a little app to teach myself some swift and I'm having some problems figuring out how to get my app to function a certain way.

My app should be able to play an airhorn sound just like the way it sounds in this video...

https://www.youtube.com/watch?v=Ks5bzvT-D6I

But each time I tap the screen repeatedly there is a slight delay before the sound is played so it's not sounding like that at all.

import UIKit
import AVFoundation

class ViewController: UIViewController {

    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        var hornSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("horn", ofType: "mp3")!)

        AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, error: nil)
        AVAudioSession.sharedInstance().setActive(true, error: nil)

        var error:NSError?
        audioPlayer = AVAudioPlayer(contentsOfURL: hornSound, error: &error)
        audioPlayer.prepareToPlay()
    }

    @IBAction func playSound(sender: UIButton) {
        audioPlayer.pause()
        audioPlayer.currentTime = 0
        audioPlayer.play()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

I have also come across this thread about using spritekit

Creating and playing a sound in swift

And in trying that I got it to play the sound without the delay, but with sprite kit I can't stop the existing sound, so they just overlap which is not the effect I want.

Is there a work around to get this working the way it sounds in the video.

Community
  • 1
  • 1
Jordan
  • 2,393
  • 4
  • 30
  • 60

1 Answers1

5

Apple recommends AVAudioPlayer for playback of audio data unless you require very low I/O latency.

So you might want to try another approach.

In one of my apps I play countdown sounds by creating a system sound ID from my wav file. Try this in your class:

import UIKit
import AudioToolbox

class ViewController: UIViewController {
    var sound: SystemSoundID = 0

    override func viewDidLoad() {
        super.viewDidLoad()

        var hornSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("horn", ofType: "mp3")!)

        AudioServicesCreateSystemSoundID(hornSound!, &self.sound)
    }

    @IBAction func playSound(sender: UIButton) {
        AudioServicesPlaySystemSound(self.sound)
    }

    ...
}
zisoft
  • 22,770
  • 10
  • 62
  • 73
  • Thank you! I had come across this before but it turns out this may have worked the first time I tried it, it turns out my audio file had a little bit of delay at the beginning the whole time -_- – Jordan Aug 04 '15 at 16:38