AlarmSound.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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 func startAlarmPlayingForTimer(time: TimeInterval) {
  28. AlarmSound.alarmPlayingForTimer = Timer.scheduledTimer(timeInterval: time,
  29. target: self,
  30. selector: #selector(AlarmSound.alarmPlayingForTimerDidEnd(_:)),
  31. userInfo: nil,
  32. repeats: true)
  33. }
  34. @objc func alarmPlayingForTimerDidEnd(_: Timer) {
  35. if !AlarmSound.isPlaying { return }
  36. AlarmSound.stop()
  37. }
  38. /*
  39. * Sets the audio volume to 0.
  40. */
  41. static func muteVolume() {
  42. audioPlayer?.volume = 0
  43. muted = true
  44. restoreSystemOutputVolume()
  45. }
  46. static func setSoundFile(str: String) {
  47. soundURL = Bundle.main.url(forResource: str, withExtension: "caf")!
  48. }
  49. /*
  50. * Sets the volume of the alarm back to the volume before it has been muted.
  51. */
  52. static func unmuteVolume() {
  53. audioPlayer?.volume = 1.0
  54. muted = false
  55. }
  56. static func stop() {
  57. Observable.shared.alarmSoundPlaying.value = false
  58. audioPlayer?.stop()
  59. audioPlayer = nil
  60. restoreSystemOutputVolume()
  61. }
  62. static func playTest() {
  63. guard !isPlaying else {
  64. return
  65. }
  66. do {
  67. audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
  68. audioPlayer!.delegate = audioPlayerDelegate
  69. try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.playback)))
  70. try AVAudioSession.sharedInstance().setActive(true)
  71. audioPlayer?.numberOfLoops = 0
  72. if !audioPlayer!.prepareToPlay() {
  73. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed preparing to play")
  74. }
  75. if audioPlayer!.play() {
  76. if !isPlaying {
  77. LogManager.shared.log(category: .alarm, message: "AlarmSound - not playing after calling play")
  78. LogManager.shared.log(category: .alarm, message: "AlarmSound - rate value: \(audioPlayer!.rate)")
  79. }
  80. } else {
  81. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed to play")
  82. }
  83. } catch {
  84. LogManager.shared.log(category: .alarm, message: "AlarmSound - unable to play sound; error: \(error)")
  85. }
  86. }
  87. static func play(repeating: Bool) {
  88. guard !isPlaying else {
  89. return
  90. }
  91. enableAudio()
  92. do {
  93. audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
  94. audioPlayer!.delegate = audioPlayerDelegate
  95. try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.playback)))
  96. try AVAudioSession.sharedInstance().setActive(true)
  97. audioPlayer!.numberOfLoops = repeating ? -1 : 0
  98. // Store existing volume
  99. if systemOutputVolumeBeforeOverride == nil {
  100. systemOutputVolumeBeforeOverride = AVAudioSession.sharedInstance().outputVolume
  101. }
  102. if !audioPlayer!.prepareToPlay() {
  103. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed preparing to play")
  104. }
  105. if audioPlayer!.play() {
  106. if !isPlaying {
  107. LogManager.shared.log(category: .alarm, message: "AlarmSound - not playing after calling play")
  108. LogManager.shared.log(category: .alarm, message: "AlarmSound - rate value: \(audioPlayer!.rate)")
  109. } else {
  110. Observable.shared.alarmSoundPlaying.value = true
  111. }
  112. } else {
  113. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed to play")
  114. }
  115. if Storage.shared.alarmConfiguration.value.overrideSystemOutputVolume {
  116. MPVolumeView.setVolume(Storage.shared.alarmConfiguration.value.forcedOutputVolume)
  117. }
  118. } catch {
  119. LogManager.shared.log(category: .alarm, message: "AlarmSound - unable to play sound; error: \(error)")
  120. }
  121. }
  122. static func playTerminated() {
  123. guard !isPlaying else {
  124. return
  125. }
  126. do {
  127. audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
  128. audioPlayer!.delegate = audioPlayerDelegate
  129. try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.playback)))
  130. try AVAudioSession.sharedInstance().setActive(true)
  131. // Play endless loops
  132. audioPlayer!.numberOfLoops = 2
  133. // Store existing volume
  134. if systemOutputVolumeBeforeOverride == nil {
  135. systemOutputVolumeBeforeOverride = AVAudioSession.sharedInstance().outputVolume
  136. }
  137. if !audioPlayer!.prepareToPlay() {
  138. LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - audio player failed preparing to play")
  139. }
  140. if audioPlayer!.play() {
  141. if !isPlaying {
  142. LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - not playing after calling play")
  143. LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - rate value: \(audioPlayer!.rate)")
  144. }
  145. } else {
  146. LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - audio player failed to play")
  147. }
  148. MPVolumeView.setVolume(1.0)
  149. } catch {
  150. LogManager.shared.log(category: .alarm, message: "Terminate AlarmSound - unable to play sound; error: \(error)")
  151. }
  152. }
  153. fileprivate static func restoreSystemOutputVolume() {
  154. guard Storage.shared.alarmConfiguration.value.overrideSystemOutputVolume else {
  155. return
  156. }
  157. // cancel any volume change observations
  158. // self.volumeChangeDetector.isActive = false
  159. // restore system output volume with its value before overriding it
  160. if let volumeBeforeOverride = systemOutputVolumeBeforeOverride {
  161. MPVolumeView.setVolume(volumeBeforeOverride)
  162. }
  163. systemOutputVolumeBeforeOverride = nil
  164. }
  165. fileprivate static func enableAudio() {
  166. do {
  167. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .mixWithOthers)
  168. try AVAudioSession.sharedInstance().setActive(true)
  169. } catch {
  170. LogManager.shared.log(category: .alarm, message: "Enable audio error: \(error)")
  171. }
  172. }
  173. }
  174. class AudioPlayerDelegate: NSObject, AVAudioPlayerDelegate {
  175. /* audioPlayerDidFinishPlaying:successfully: is called when a sound has finished playing. This method is NOT called if the player is stopped due to an interruption. */
  176. func audioPlayerDidFinishPlaying(_: AVAudioPlayer, successfully flag: Bool) {
  177. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerDidFinishPlaying (\(flag))", isDebug: true)
  178. Observable.shared.alarmSoundPlaying.value = false
  179. }
  180. /* if an error occurs while decoding it will be reported to the delegate. */
  181. func audioPlayerDecodeErrorDidOccur(_: AVAudioPlayer, error: Error?) {
  182. if let error = error {
  183. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerDecodeErrorDidOccur: \(error)")
  184. } else {
  185. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerDecodeErrorDidOccur")
  186. }
  187. }
  188. /* AVAudioPlayer INTERRUPTION NOTIFICATIONS ARE DEPRECATED - Use AVAudioSession instead. */
  189. /* audioPlayerBeginInterruption: is called when the audio session has been interrupted while the player was playing. The player will have been paused. */
  190. func audioPlayerBeginInterruption(_: AVAudioPlayer) {
  191. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerBeginInterruption")
  192. Observable.shared.alarmSoundPlaying.value = false
  193. }
  194. /* audioPlayerEndInterruption:withOptions: is called when the audio session interruption has ended and this player had been interrupted while playing. */
  195. /* Currently the only flag is AVAudioSessionInterruptionFlags_ShouldResume. */
  196. func audioPlayerEndInterruption(_: AVAudioPlayer, withOptions flags: Int) {
  197. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerEndInterruption withOptions: \(flags)")
  198. Observable.shared.alarmSoundPlaying.value = false
  199. }
  200. }
  201. // Helper function inserted by Swift 4.2 migrator.
  202. private func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String {
  203. return input.rawValue
  204. }
  205. extension MPVolumeView {
  206. static func setVolume(_ volume: Float) {
  207. // Need to use the MPVolumeView in order to change volume, but don't care about UI set so frame to .zero
  208. let volumeView = MPVolumeView(frame: .zero)
  209. // Search for the slider
  210. let slider = volumeView.subviews.first(where: { $0 is UISlider }) as? UISlider
  211. // Update the slider value with the desired volume.
  212. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) {
  213. slider?.value = volume
  214. }
  215. // Optional - Remove the HUD
  216. if let app = UIApplication.shared.delegate as? AppDelegate, let window = app.window {
  217. volumeView.alpha = 0.000001
  218. window.addSubview(volumeView)
  219. }
  220. }
  221. }