Low latency audio playback

I have a sound in my application that starts automatically when a view appears; but, as the name says, I would like this sound to start with a slight delay, about half a second after the appearance of the performance. I tried using PlayAtTime, but either it doesn’t work, or I misunderstood something ... This is my code:

var player = AVAudioPlayer? override func viewDidLoad() { super.viewDidLoad() playAudioWithDelay() } func playAudioWithDelay() { let file = NSBundle.mainBundle().URLForResource("PR1", withExtension: "wav") player = AVAudioPlayer(contentsOfURL: file, error: nil) player!.volume = 0.5 player!.numberOfLoops = -1 player!.playAtTime(//I tried with 0.5 but doesn't work) player!.prepareToPlay() player!.play() } 
+1
source share
2 answers

You can try:

 let seconds = 1.0//Time To Delay let delay = seconds * Double(NSEC_PER_SEC) // nanoseconds per seconds var dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(dispatchTime, dispatch_get_main_queue(), { //Play Sound here }) 

Full code:

 func playAudioWithDelay() { let file = NSBundle.mainBundle().URLForResource("PR1", withExtension: "wav") player = AVAudioPlayer(contentsOfURL: file, error: nil) player!.volume = 0.5 player!.numberOfLoops = -1 player!.playAtTime(//I tried with 0.5 but doesn't work) player!.prepareToPlay() let seconds = 1.0//Time To Delay let delay = seconds * Double(NSEC_PER_SEC) // nanoseconds per seconds var dispatchTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay)) dispatch_after(dispatchTime, dispatch_get_main_queue(), { player!.play() }) } 
+4
source

Try the following function in Swift 3.0

  var player: AVAudioPlayer? func playAudioWithDelay() { let file = Bundle.main.url(forResource: "PR1", withExtension: "wav") do { player = try AVAudioPlayer(contentsOf: file!) player?.volume = 0.5 player?.numberOfLoops = -1 player?.prepareToPlay() } catch let error as NSError { print("error: \(error.localizedDescription)") } let seconds = 1.0//Time To Delay let when = DispatchTime.now() + seconds DispatchQueue.main.asyncAfter(deadline: when) { self.play() } } func play() { if player?.isPlaying == false { player?.play() } } 
0
source

Source: https://habr.com/ru/post/1264748/


All Articles