【问题标题】:Swift 2.0 Playing custom sound in app delegate while in background modeSwift 2.0 在后台模式下在应用程序委托中播放自定义声音
【发布时间】:2015-11-16 10:57:09
【问题描述】:

我正在使用 Google Cloud 消息传递将通知推送到我用 Swift 2.0 xCode 7.1 编写的 iOS 应用程序。 GCM 不允许自定义通知声音。 见这里:https://developers.google.com/cloud-messaging/http-server-ref

所以我关闭了默认声音,并尝试在调用“didReceiveRemoteNotification”时播放声音。我的问题是在后台模式下没有播放声音。但是如果我将代码(下面)放在“didFinishLaunchingWithOptions”中,它可以完美地工作,只是在我想要它播放的时候不行。 我在 info.plist 中添加了更多背景。就像我说的那样,它只是在推送通知到达时才起作用。

    let alertSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("GMNotification", ofType: "wav")!)
    print(alertSound)

    //var error:NSError?
    do {
        try self.audioPlayer = AVAudioPlayer(contentsOfURL: alertSound, fileTypeHint:nil)
        self.audioPlayer.prepareToPlay()
        self.audioPlayer.play()
        print("PLAY !!!")
    } catch {
        print("Error ???")
    }

有人可以帮忙吗?

【问题讨论】:

  • 要在后台模式下播放音乐,您需要在 Info-Plist-Background-modes 中注册为音乐应用程序。
  • 嗨克里斯蒂安,我已经从我的信息列表中添加了我的背景模式。
  • 也许这个stackoverflow.com/questions/16232315/… 可以帮助你。
  • 你解决了这个问题吗?我面临同样的问题。解决方案应该是自定义通知然后显示它,但我不知道如何快速做到这一点(我在 android tho' 中取得了成功)。

标签: ios avaudioplayer


【解决方案1】:

您必须创建一个共享实例“Singelton”才能播放声音。返回参考:

Swift - AVAudioPlayer, sound doesn't play correctly

这应该告诉你如何做到这一点

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-20
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-11
    • 2011-08-15
    • 1970-01-01
    相关资源
    最近更新 更多