Playing a sound while app is in the foreground and the screen is locked - iOS

后端 未结 2 949
南笙
南笙 2021-01-31 10:43

Preface: I\'m building an alarm clock app. Many other alarm apps such as Alarm Clock Pro are able to play an alarm while the screen is locked and the app is in the foreground. T

相关标签:
2条回答
  • 2021-01-31 11:12

    See my response above. Basically though

    I ended up using https://github.com/mruegenberg/MMPDeepSleepPreventer

    I ran it in it's own separate xCode project and it only uses 0.5% of the cpu when the app is in the background. It turns out it was my code that was killing the cpu. All is well now!

    0 讨论(0)
  • 2021-01-31 11:14

    Even if your app is in the foreground when the device is on, after it's locked it will go to background (willresignactive is called). Now from what I gathered around the internet you should not be looping the sound yourself but instead provide the custom music file in one of these formats in your main app bundle:

    • Linear PCM
    • MA4 (IMA/ADPCM)
    • µLaw
    • aLaw

    The custom sound can only be 30 seconds or less. After initializing your UILocalNotification object you need to set its firedate property, which is date and time (also recurring) for firing the notification. Then you set the alert message through alertBody (like "wake up") and the string on the alert button through alertAction. The file name of the custom sound goes into the soundName property. You present your notification instance by calling scheduleLocalNotification:, a UIApplication method. Note that the time you call this method does not need to be, and usually is not, the time when the notification will fire.And you only need to call this once even if you set a recurring notification.You cancel it by calling cancelLocalNotification: . Now your alarm should play whether your app is in foreground, background or not even open.

    It's all in here.

    0 讨论(0)
提交回复
热议问题