ios - 应用程序在后台 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)
}
}
我希望有人能指出这个问题。
解决方案
推荐阅读
- java - Java中的空白字符常量
- r - 如果缺失值满足数据集中的某个值,我该如何填充?
- ms-access - 一个报表可以有多个记录源吗?
- mysql - Mysql - 检查任何指向父母的孩子
- python - Django:使用related_name添加2个外键引用同一个表导致NameError - 未定义相关名称的值
- javascript - 如何处理 Amchart 4 光标高度?
- json - 如何将具有唯一标识符(eventID/UUID/filename)的消息密钥从 Nifi 发送到 Kafka 主题并在 kafka 日志中查看
- php - 在 PHP 和 MySQL 中使用 ENUM 指定用户或管理员会话
- mysql - 选择具有最高列值的行
- php - 当我更改购物车中产品的数量时,总价不变(PHP)