【问题标题】:Is it possible to play a sound from an app in background是否可以在后台播放来自应用程序的声音
【发布时间】: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")

【问题讨论】:

标签: ios swift avaudioplayer ibeacon


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-04-20
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多