播放声音有点延迟

时间:2015-08-05 18:25:37

标签: swift avfoundation avaudioplayer playback

我的应用中有一个声音会在出现视图时自动启动;但是,正如标题所说的那样,我希望这个声音在视图出现后大约半秒钟后会有一点延迟。我尝试使用PlayAtTime,但是它不起作用或者我设置了一些错误的东西...... 这是我的代码:

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

3 个答案:

答案 0 :(得分:4)

你可以试试这个:

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

答案 1 :(得分:0)

尝试在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()
    }
}

答案 2 :(得分:0)

快速5音频延迟设置:

 var player: AVAudioPlayer?

func playAudio(soundName: String, extension: String, delay: Double)
{
    let file = Bundle.main.url(forResource: soundName, withExtension: extension)

    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 = delay//Time To Delay
    let when = DispatchTime.now() + seconds

    DispatchQueue.main.asyncAfter(deadline: when) {
        player.play()
    }
}