Search code examples
swiftavfoundationavaudioplayerplayback

Play sound with a little delay


I have a sound in my app that starts automatically when appear the view; but, as the title says, I'd like that this sounds starts with a little delay, about an half second after the view appear. I tried to use PlayAtTime, but or it does not work or I have set somethings wrong... 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()
}

Solution

  • You can try using this:

    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()
        })
    }