在通知中播放歌曲
Posted
技术标签:
【中文标题】在通知中播放歌曲【英文标题】:Play song in Notification 【发布时间】:2017-04-05 07:41:18 【问题描述】:我想播放一首歌。当通知到来时。当应用程序处于前台模式时,我的代码工作正常。我想在应用程序处于后台模式时播放歌曲。请帮忙。
【问题讨论】:
【参考方案1】:为您的本地通知添加自定义声音
Swift 3.0
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any])
var state: UIApplicationState = application.applicationState
if state == .active
var soundID: SystemSoundID
var mainBundle: CFBundleRef = CFBundleGetMainBundle()
var ref: CFURLRef? = CFBundleCopyResourceURL(mainBundle, ("mySoundName.wav" as? CFString), nil, nil)
AudioservicesCreateSystemSoundID(ref, soundID)
AudioServicesPlaySystemSound(soundID)
else
// Push Notification received in the background
对于推送通知 将此添加到有效负载..
aps =
alert = "message";
sound = "pushSound.caf";//this file will have to your bundle
;
【讨论】:
添加了3.0版本。【参考方案2】:您需要在 plist 文件中进行一些更改。
1.) 将必需的后台模式设置为应用播放音频。
2.) 将应用程序不在后台运行设置为是
代码
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any])
var state: UIApplicationState = application.applicationState
if state == .active
print("User Info : \(userInfo.description)")
print("User Info Alert Message : \(userInfo["aps"]["alert"])")
var messageString: String? = "\((userInfo["aps"] as? String)?["alert"] as? String)"
var playSoundOnAlert: String? = "\((userInfo["aps"] as? String)?["sound"] as? String)"
var url = URL(fileURLWithPath: "\(Bundle.main.resourcePath)/\(playSoundOnAlert)")
var error: Error?
audioPlayer = try? AVAudioPlayer(contentsOf: url)
audioPlayer.numberOfLoops = 0
audioPlayer.play()
【讨论】:
以上是关于在通知中播放歌曲的主要内容,如果未能解决你的问题,请参考以下文章