gpt4 book ai didi

ios - 在 iOS 上开始在后台播放声音?

转载 作者:可可西里 更新时间:2023-11-01 04:43:24 26 4
gpt4 key购买 nike

我正在尝试做类似于 Tile.app 的事情.当它显示通知时,它会播放声音。这看起来很简单——使用 UILocalNotification 并包含声音文件名。但是本地通知将声音限制在不超过 30 秒,而 Tile 的声音持续播放的时间比这长得多。我预计它会循环播放,并且一直持续到我再也无法忍受噪音为止。

即使手机的静音开关打开,声音也会播放,本地通知不会发生这种情况。由于这些原因,UILocalNotification 似乎已经过时了。

我想也许我可以发布纯文本本地通知并让我的应用程序播放声音。但是使用AVAudioPlayerplay方法返回NO,声音不播放。

Other questions已经建议这是设计使然,应用程序不应该能够从后台播放声音 - 只能继续已经播放的声音。我会接受这种推理,除非 Tile 做到了,所以这显然是可能的。一suggested workaround以某种方式违反了 Apple 的准则,我很确定 Apple 现在会检查。

一些可能相关的细节:

  • 我在 Info.plist 中有 audio 背景模式
  • 我在 Audio Session 上使用了 AVAudioSessionCategoryPlayback,并且该 session 应该处于事件状态(至少,setActive:error: 声称成功)。
  • 此应用使用蓝牙,但目前不使用 bluetooth-central 后台模式。

最佳答案

实际上您可以使用 AudioServices... 之一功能

  • AudioServicesPlaySystemSound
  • AudioServicesPlayAlertSound
  • AudioServicesPlaySystemSoundWithCompletion

开始在后台播放声音。

我不确定可以提交给 AudioServicesCreateSystemSoundID 的声音长度因为我只检查了短循环声音是否响铃,但此 API 未绑定(bind)通知,因此可能会超过 30 秒限制。

编辑:应用程序仍然需要 audioUIBackgroundModes在后台播放

截 self 的测试项目appDelegate,iOS 9.3.1

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// test sound in foreground.
registerAndPlaySound()

return true
}

func applicationDidEnterBackground(application: UIApplication) {
var task = UIBackgroundTaskInvalid
task = application.beginBackgroundTaskWithName("time for music") {
application.endBackgroundTask(task)
}
// dispatch not required, it's just to simulate "deeper" background
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC)))

dispatch_after(delayTime, dispatch_get_main_queue()) {
self.registerAndPlaySound()
}
}

func registerAndPlaySound() {
var soundId: SystemSoundID = 0

let bundle = NSBundle.mainBundle()
guard let soundUrl = bundle.URLForResource("InboundCallRing", withExtension: "wav") else {
return
}
AudioServicesCreateSystemSoundID(soundUrl, &soundId)

AudioServicesPlayAlertSound(soundId)
}

更新

我在那里使用了beginBackgroundTask仅启动声音作为在另一个项目的后台执行代码的最简单方法,类似于 registerAndPlaySound被调用自 PushKit没有后台任务的回调。

关于ios - 在 iOS 上开始在后台播放声音?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37351815/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com