Start playing sound in background on iOS?

随声附和 提交于 2019-11-30 14:53:05

Actually you can use one of AudioServices... functions

  • AudioServicesPlaySystemSound
  • AudioServicesPlayAlertSound
  • AudioServicesPlaySystemSoundWithCompletion

to start playing sound in background.

I'm not sure about length of sound that can be submitted to AudioServicesCreateSystemSoundID because I'm checked only with short looped sound for ringing but this API not tied to notification so possible can overpass 30 second limit.

EDIT: App still requires audio in UIBackgroundModes to play in background

Cut from my test project 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)
}

Update

There I used beginBackgroundTask to start sound only as simplest way to execute code in background in another project similar code to registerAndPlaySound was called from PushKit callback without background task.

From official Apple documentation:

"Custom sounds must be under 30 seconds when played. If a custom sound is over that limit, the default system sound is played instead."

There is no way that you can make UILocalNotication to loop the sound. You can schedule it again with time intervals for 30s, but that one will be a schedulation of another alarm.

To setup your custom notification sound:

notif.soundName = @"sound.caf";

Make sure the sound is actually in your app’s bundle, is in the correct format (linear PCM or IMA4—pretty much anywhere that explains how to convert sounds for iOS will tell you how to do that), and is under 30 seconds.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!