Play sound effect without delay
I am trying to make a small application to learn it myself quickly and am having trouble figuring out how to get my application to function in a certain way.
My application should be able to play a beep similar to the sound that sounds in this video ...
https://www.youtube.com/watch?v=Ks5bzvT-D6I
But every time I click on the screen multiple times, there is a slight delay before the sound plays, so it doesn't sound 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 also ran into this issue about using spritekit
And trying to get me to play the sound without delay, but with the sprite kit, I can't stop the existing sound, so they just overlap, which is not the effect I want.
Is there any work in progress to make this work as it sounds in the video.
source to share
Apple recommends AVAudioPlayer
for playing audio data unless you require very low I / O latency.
So, you can try a different approach.
In one of my applications, I am playing 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)
}
...
}
source to share