稍微延迟播放声音 [英] Play sound with a little delay

查看:120
本文介绍了稍微延迟播放声音的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中出现声音,该声音会在出现视图时自动启动;但是,正如标题所说,我希望声音稍微延迟一些,大约在视图出现后半秒钟开始.我尝试使用PlayAtTime,但是还是无法正常工作,或者我设置了一些错误... 这是我的代码:

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

推荐答案

您可以尝试使用此方法:

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

完整代码:

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

这篇关于稍微延迟播放声音的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆