首页 > 解决方案 > 应用程序在后台 AVAudioSession 中时如何播放自定义声音?

问题描述

我的 iOS 应用程序从我们的主服务接收到刷新其状态的通知。现在,我们正在获取最新状态,并在有更新数据时播放持续声音。我们的设备被锁定在引导模式以阻止它们关闭。

我们正在进行更改,以便设备可以在 xx 分钟不活动后进入睡眠状态。但是,我们注意到应用程序在后台时不会播放声音,而且似乎总是在AVAudioSession.sharedInstance().setActive(true). 有趣的是,如果放置断点并通过调试器运行它,它可以正常工作,但是当正常运行时,它会失败并出现以下错误:

Error Domain=NSOSStatusErrorDomain Code=561015905

我们在功能下的后台模式下启用了“音频、AirPlay 和 PnP”。下面是播放声音的代码:

func playSound(shouldPlay: Bool) {
        guard let url = Bundle.main.url(forResource: "sms_alert_circles", withExtension: "caf") else { return }

        let audioSession = AVAudioSession.sharedInstance()

            do {
                try self.audioSession.setCategory(.playback, mode: .default, options: .mixWithOthers)
                try self.audioSession.setActive(true)

                /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
                self.player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.caf.rawValue)

                guard let player = self.player else { return }

                if shouldPlay == true {
                    player.volume = 1.0
                    player.numberOfLoops = 1
                    player.play()
                } else {
                    player.stop()
                    try self.audioSession.setActive(false)
                }

            } catch let error {
                print("Error playing sounds")
                print(error.localizedDescription)
            }
        
    }

我希望有人能指出这个问题。

标签: iosswiftavaudiosession

解决方案


推荐阅读