是否可以在后台播放来自应用程序的声音

时间:2020-10-27 13:32:47

标签: ios swift avaudioplayer ibeacon

我正在使用iOS应用程序,该应用程序连接到iBeacon。 如果外部参数匹配,我希望能够播放手机的声音。 我启用了“音频,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")

1 个答案:

答案 0 :(得分:0)

如果您将应用程序设置为侦听信标区域通知,则即使手机已锁定和/或您的应用程序未运行,也可以在进入或离开区域时触发声音播放。我不确定如果用户将手机静音(我怀疑不是),这些声音是否会播放