【问题标题】:AVAudioPlayer produces lag in Swift 4.2AVAudioPlayer 在 Swift 4.2 中产生延迟
【发布时间】:2018-11-23 16:20:33
【问题描述】:

是的,我不是第一个提出这个问题的人,但我发现的一切都像是 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)"

感谢您的帮助和建议!

【问题讨论】:

  • 嗨,伙计。通过 SetSoundinBackground() 方法将声音发送到后台是什么意思?
  • 该方法可以让应用在后台使用声音。

标签: swift avaudioplayer


【解决方案1】:

好吧,解决方案似乎很简单。我将此添加到我的 SoundCollectStaff() 函数中:

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

【讨论】:

    猜你喜欢
    • 2014-10-19
    • 2012-01-03
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2014-03-16
    • 2011-09-05
    • 1970-01-01
    相关资源
    最近更新 更多