AlarmSound.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. // LoopFollow
  2. // AlarmSound.swift
  3. import AVFoundation
  4. import Foundation
  5. import MediaPlayer
  6. import UIKit
  7. /*
  8. * Class that handles the playing and the volume of the alarm sound.
  9. */
  10. class AlarmSound {
  11. static var isPlaying: Bool {
  12. return audioPlayer?.isPlaying == true
  13. }
  14. static var isMuted: Bool {
  15. return muted
  16. }
  17. static var whichAlarm: String = "none"
  18. static var soundFile = "Indeed"
  19. static var isTesting: Bool = false
  20. fileprivate static var systemOutputVolumeBeforeOverride: Float?
  21. fileprivate static var soundURL = Bundle.main.url(forResource: "Indeed", withExtension: "caf")!
  22. fileprivate static var audioPlayer: AVAudioPlayer?
  23. fileprivate static let audioPlayerDelegate = AudioPlayerDelegate()
  24. fileprivate static var muted = false
  25. fileprivate static var alarmPlayingForTimer = Timer()
  26. fileprivate static let alarmPlayingForInterval = 290
  27. fileprivate static var repeatDelay: TimeInterval = 0
  28. fileprivate func startAlarmPlayingForTimer(time: TimeInterval) {
  29. AlarmSound.alarmPlayingForTimer = Timer.scheduledTimer(timeInterval: time,
  30. target: self,
  31. selector: #selector(AlarmSound.alarmPlayingForTimerDidEnd(_:)),
  32. userInfo: nil,
  33. repeats: true)
  34. }
  35. @objc func alarmPlayingForTimerDidEnd(_: Timer) {
  36. if !AlarmSound.isPlaying { return }
  37. AlarmSound.stop()
  38. }
  39. /*
  40. * Sets the audio volume to 0.
  41. */
  42. static func muteVolume() {
  43. audioPlayer?.volume = 0
  44. muted = true
  45. restoreSystemOutputVolume()
  46. }
  47. static func setSoundFile(str: String) {
  48. soundURL = Bundle.main.url(forResource: str, withExtension: "caf")!
  49. }
  50. /*
  51. * Sets the volume of the alarm back to the volume before it has been muted.
  52. */
  53. static func unmuteVolume() {
  54. audioPlayer?.volume = 1.0
  55. muted = false
  56. }
  57. static func stop() {
  58. Observable.shared.alarmSoundPlaying.value = false
  59. repeatDelay = 0
  60. audioPlayer?.stop()
  61. audioPlayer = nil
  62. restoreSystemOutputVolume()
  63. }
  64. static func playTest() {
  65. guard !isPlaying else {
  66. return
  67. }
  68. do {
  69. audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
  70. audioPlayer!.delegate = audioPlayerDelegate
  71. activateAudioSessionWithFallback()
  72. audioPlayer?.numberOfLoops = 0
  73. if !audioPlayer!.prepareToPlay() {
  74. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed preparing to play")
  75. }
  76. if audioPlayer!.play() {
  77. if !isPlaying {
  78. LogManager.shared.log(category: .alarm, message: "AlarmSound - not playing after calling play")
  79. LogManager.shared.log(category: .alarm, message: "AlarmSound - rate value: \(audioPlayer!.rate)")
  80. }
  81. } else {
  82. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed to play")
  83. }
  84. } catch {
  85. LogManager.shared.log(category: .alarm, message: "AlarmSound - unable to play sound; error: \(error)")
  86. }
  87. }
  88. static func play(repeating: Bool, delay: Int = 0) {
  89. guard !isPlaying else {
  90. return
  91. }
  92. // If repeating with delay, we'll handle it manually via the delegate
  93. // Only set repeatDelay if both repeating and delay > 0
  94. repeatDelay = (repeating && delay > 0) ? TimeInterval(delay) : 0
  95. do {
  96. audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
  97. audioPlayer!.delegate = audioPlayerDelegate
  98. activateAudioSessionWithFallback()
  99. // Only use numberOfLoops if we're not using delay-based repeating
  100. // When repeatDelay > 0, we play once and then use the delegate to schedule the next play with delay
  101. audioPlayer!.numberOfLoops = (repeating && repeatDelay == 0) ? -1 : 0
  102. // Store existing volume
  103. if systemOutputVolumeBeforeOverride == nil {
  104. systemOutputVolumeBeforeOverride = AVAudioSession.sharedInstance().outputVolume
  105. }
  106. if !audioPlayer!.prepareToPlay() {
  107. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed preparing to play")
  108. }
  109. // First sound plays immediately - delay only applies between repeated sounds
  110. if audioPlayer!.play() {
  111. if !isPlaying {
  112. LogManager.shared.log(category: .alarm, message: "AlarmSound - not playing after calling play (rate \(audioPlayer!.rate))")
  113. } else {
  114. Observable.shared.alarmSoundPlaying.value = true
  115. if repeatDelay > 0 {
  116. LogManager.shared.log(category: .alarm, message: "AlarmSound - first sound playing immediately, delay (\(repeatDelay)s) will apply between repeats")
  117. }
  118. }
  119. } else {
  120. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed to play")
  121. }
  122. if Storage.shared.alarmConfiguration.value.overrideSystemOutputVolume {
  123. MPVolumeView.setVolume(Storage.shared.alarmConfiguration.value.forcedOutputVolume)
  124. }
  125. } catch {
  126. LogManager.shared.log(category: .alarm, message: "AlarmSound - unable to play sound; error: \(error)")
  127. }
  128. }
  129. fileprivate static func playNextWithDelay() {
  130. guard repeatDelay > 0 else {
  131. return
  132. }
  133. DispatchQueue.main.asyncAfter(deadline: .now() + repeatDelay) {
  134. // Check if we should still be playing (user might have stopped it)
  135. guard repeatDelay > 0 else {
  136. return
  137. }
  138. // Clean up the previous player
  139. audioPlayer?.stop()
  140. audioPlayer = nil
  141. do {
  142. audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
  143. audioPlayer!.delegate = audioPlayerDelegate
  144. activateAudioSessionWithFallback()
  145. audioPlayer!.numberOfLoops = 0
  146. if !audioPlayer!.prepareToPlay() {
  147. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed preparing to play (delayed repeat)")
  148. }
  149. if audioPlayer!.play() {
  150. Observable.shared.alarmSoundPlaying.value = true
  151. } else {
  152. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed to play (delayed repeat)")
  153. }
  154. } catch {
  155. LogManager.shared.log(category: .alarm, message: "AlarmSound - unable to play sound (delayed repeat); error: \(error)")
  156. }
  157. }
  158. }
  159. static func playTerminated() {
  160. guard !isPlaying else {
  161. return
  162. }
  163. do {
  164. audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
  165. audioPlayer!.delegate = audioPlayerDelegate
  166. activateAudioSessionWithFallback()
  167. // Play endless loops
  168. audioPlayer!.numberOfLoops = 2
  169. // Store existing volume
  170. if systemOutputVolumeBeforeOverride == nil {
  171. systemOutputVolumeBeforeOverride = AVAudioSession.sharedInstance().outputVolume
  172. }
  173. if !audioPlayer!.prepareToPlay() {
  174. LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - audio player failed preparing to play")
  175. }
  176. if audioPlayer!.play() {
  177. if !isPlaying {
  178. LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - not playing after calling play")
  179. LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - rate value: \(audioPlayer!.rate)")
  180. }
  181. } else {
  182. LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - audio player failed to play")
  183. }
  184. MPVolumeView.setVolume(1.0)
  185. } catch {
  186. LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - unable to play sound; error: \(error)")
  187. }
  188. }
  189. fileprivate static func restoreSystemOutputVolume() {
  190. guard Storage.shared.alarmConfiguration.value.overrideSystemOutputVolume else {
  191. return
  192. }
  193. // cancel any volume change observations
  194. // self.volumeChangeDetector.isActive = false
  195. // restore system output volume with its value before overriding it
  196. if let volumeBeforeOverride = systemOutputVolumeBeforeOverride {
  197. MPVolumeView.setVolume(volumeBeforeOverride)
  198. }
  199. systemOutputVolumeBeforeOverride = nil
  200. }
  201. // Background activation of a non-mixable .playback session is denied by iOS
  202. // (cannotInterruptOthers, 560557684) unless the app is already actively playing
  203. // audio. In foreground, or with Silent Tune holding a mixable session alive,
  204. // options: [] succeeds and lets the alarm dominate other audio. For
  205. // Bluetooth-heartbeat users with no Silent Tune we skip [] (it would always
  206. // be denied) and ladder through mixable options so activation is still
  207. // permitted from background. Each attempt is logged so we can see in the
  208. // field which fallback (if any) the user landed on.
  209. fileprivate static func activateAudioSessionWithFallback() {
  210. let isBackgroundWithoutSilentTune = UIApplication.shared.applicationState == .background
  211. && Storage.shared.backgroundRefreshType.value != .silentTune
  212. let dominate: (label: String, options: AVAudioSession.CategoryOptions) = ("[]", [])
  213. let duck: (label: String, options: AVAudioSession.CategoryOptions) = (".duckOthers", .duckOthers)
  214. let mix: (label: String, options: AVAudioSession.CategoryOptions) = (".mixWithOthers", .mixWithOthers)
  215. let candidates = isBackgroundWithoutSilentTune ? [duck, mix] : [dominate, duck, mix]
  216. for candidate in candidates {
  217. do {
  218. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: candidate.options)
  219. try AVAudioSession.sharedInstance().setActive(true)
  220. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio session active (options: \(candidate.label))")
  221. return
  222. } catch {
  223. let nsError = error as NSError
  224. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio session activation failed (options: \(candidate.label)) [code \(nsError.code)]: \(error.localizedDescription)")
  225. }
  226. }
  227. LogManager.shared.log(category: .alarm, message: "AlarmSound - all audio session option fallbacks exhausted")
  228. }
  229. }
  230. class AudioPlayerDelegate: NSObject, AVAudioPlayerDelegate {
  231. /* audioPlayerDidFinishPlaying:successfully: is called when a sound has finished playing. This method is NOT called if the player is stopped due to an interruption. */
  232. func audioPlayerDidFinishPlaying(_: AVAudioPlayer, successfully flag: Bool) {
  233. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerDidFinishPlaying (\(flag))", isDebug: true)
  234. // If we're repeating with delay, schedule the next play
  235. if AlarmSound.repeatDelay > 0 {
  236. AlarmSound.playNextWithDelay()
  237. } else {
  238. Observable.shared.alarmSoundPlaying.value = false
  239. }
  240. }
  241. /* if an error occurs while decoding it will be reported to the delegate. */
  242. func audioPlayerDecodeErrorDidOccur(_: AVAudioPlayer, error: Error?) {
  243. if let error = error {
  244. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerDecodeErrorDidOccur: \(error)")
  245. } else {
  246. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerDecodeErrorDidOccur")
  247. }
  248. }
  249. /* AVAudioPlayer INTERRUPTION NOTIFICATIONS ARE DEPRECATED - Use AVAudioSession instead. */
  250. /* audioPlayerBeginInterruption: is called when the audio session has been interrupted while the player was playing. The player will have been paused. */
  251. func audioPlayerBeginInterruption(_: AVAudioPlayer) {
  252. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerBeginInterruption")
  253. Observable.shared.alarmSoundPlaying.value = false
  254. }
  255. /* audioPlayerEndInterruption:withOptions: is called when the audio session interruption has ended and this player had been interrupted while playing. */
  256. /* Currently the only flag is AVAudioSessionInterruptionFlags_ShouldResume. */
  257. func audioPlayerEndInterruption(_: AVAudioPlayer, withOptions flags: Int) {
  258. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerEndInterruption withOptions: \(flags)")
  259. Observable.shared.alarmSoundPlaying.value = false
  260. }
  261. }
  262. // Helper function inserted by Swift 4.2 migrator.
  263. private func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String {
  264. return input.rawValue
  265. }
  266. extension MPVolumeView {
  267. static func setVolume(_ volume: Float) {
  268. // Need to use the MPVolumeView in order to change volume, but don't care about UI set so frame to .zero
  269. let volumeView = MPVolumeView(frame: .zero)
  270. // Search for the slider
  271. let slider = volumeView.subviews.first(where: { $0 is UISlider }) as? UISlider
  272. // Update the slider value with the desired volume.
  273. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) {
  274. slider?.value = volume
  275. }
  276. // Optional - Remove the HUD
  277. let activeWindow = UIApplication.shared.connectedScenes
  278. .compactMap { $0 as? UIWindowScene }
  279. .first { $0.activationState == .foregroundActive }?
  280. .windows.first(where: \.isKeyWindow)
  281. if let window = activeWindow {
  282. volumeView.alpha = 0.000001
  283. window.addSubview(volumeView)
  284. }
  285. }
  286. }