首页 > 解决方案 > AVAudioPlayer 在 Swift 4.2 中产生延迟

问题描述

是的,我不是第一个提出这个问题的人,但我发现的一切都像是 4 岁,我找不到解决这个问题的方法。可能我只是不明白解决方案。

问题:

每次我在设备上启动应用程序并调用我的“声音”文件时,它都会滞后一会儿。我试图将声音设置为背景,但它仍然滞后。我还在应用程序的项目设置中为背景模式(音频、AirPlay 和画中画)设置了 Capabilitis 选项。

无论出于何种原因,在“背景”中调用“声音”都可以在 Xcode 的模拟器中正常工作,没有任何滞后。

我正在使用此代码调用 m4a 格式的声音文件:

var SoundCollect: AVAudioPlayer?

func SoundCollectStaff() {

do {

        if let fileURL = Bundle.main.path(forResource: "collect", ofType: "m4a") {

            SoundCollect = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: fileURL))

            SoundCollect?.prepareToPlay()
            SoundCollect?.play()

        } else {

         print("no file found")
        }

} catch let error {
    print("error failed with: \(error.localizedDescription)")
    }
}

这段代码将声音设置为背景

func SetSoundinBackground() {

    do {

        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers, .allowAirPlay])
        try AVAudioSession.sharedInstance().setActive(true)
        print("Session is Active")

    } catch {
        print(error)
    }

}

通过调用 SetSoundinBackground() 函数,我在设备上得到以下信息Error: Error Domain=NSOSStatusErrorDomain Code=-50 "(null)"

感谢您的任何帮助和建议!

标签: swiftavaudioplayer

解决方案


那么解决方案似乎很容易。我将此添加到我的 SoundCollectStaff() 函数中:

DispatchQueue.global().async { SoundCollect.play() }


推荐阅读