【发布时间】:2020-10-27 13:32:47
【问题描述】:
我正在开发一个连接到 iBeacon 的 iOS 应用程序。 如果外部参数匹配,我希望能够从手机播放声音。 我已启用“音频、Airplay 和画中画”。在后台模式中。
现在我有一个问题,它只能播放来自应用程序的声音,而:
- 应用在前台。
- 屏幕被锁定,手机没有静音。
我希望它也能够播放声音,同时:
- 锁屏和手机静音。
- 后台(当应用由 iBeacon 启动时)。
有什么办法可以做到吗?
我用来播放声音的功能是:
private var avPlayer: AVAudioPlayer?
// MARK: - Play Sound
internal func playSound(forResource resource: String, ofType type: String) {
guard let path = Bundle.main.path(forResource: resource, ofType: type) else {
print("Test: Failed getting path for \(resource)")
return
}
let url = URL(fileURLWithPath: path)
// Handle playing in background
let session = AVAudioSession.sharedInstance()
do {
try session.setCategory(.playback, options: [.duckOthers])
try session.setActive(true, options: .notifyOthersOnDeactivation)
} catch {
print("Test: Failed setting category on session \(error)")
}
do {
avPlayer = try AVAudioPlayer(contentsOf: url)
} catch let error {
print("Test: Failed adding url to AVAudioPlayer \(error)")
}
avPlayer?.play()
}
并称其为:
playSound(forResource: "SoundToPlay", ofType: "wav")
【问题讨论】:
-
@KirilS。音频、Airplay 和画中画。在后台模式下启用。
标签: ios swift avaudioplayer ibeacon