AVAudioPlayer在Swift 4.2中产生滞后现象

时间:2018-11-23 16:20:34

标签: swift avaudioplayer

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

问题:

每次我在设备上启动APP并调用“声音”文件时,它都会停顿一会儿。我试图将声音设置为背景,但仍然滞后。另外,我还在应用程序的项目设置中为背景模式(音频,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)"

感谢您的帮助和建议!

1 个答案:

答案 0 :(得分:0)

该解决方案似乎很简单。我将其添加到我的SoundCollectStaff()函数中:

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