AlarmSound.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273
  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 playingTimer: Timer?
  22. fileprivate static var soundURL = Bundle.main.url(forResource: "Indeed", withExtension: "caf")!
  23. fileprivate static var audioPlayer: AVAudioPlayer?
  24. fileprivate static let audioPlayerDelegate = AudioPlayerDelegate()
  25. fileprivate static var muted = false
  26. fileprivate static var alarmPlayingForTimer = Timer()
  27. fileprivate static let alarmPlayingForInterval = 290
  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. playingTimer?.invalidate()
  59. playingTimer = nil
  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. try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.playback)))
  72. try AVAudioSession.sharedInstance().setActive(true)
  73. audioPlayer?.numberOfLoops = 0
  74. if !audioPlayer!.prepareToPlay() {
  75. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed preparing to play")
  76. }
  77. if audioPlayer!.play() {
  78. if !isPlaying {
  79. LogManager.shared.log(category: .alarm, message: "AlarmSound - not playing after calling play")
  80. LogManager.shared.log(category: .alarm, message: "AlarmSound - rate value: \(audioPlayer!.rate)")
  81. }
  82. } else {
  83. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed to play")
  84. }
  85. } catch {
  86. LogManager.shared.log(category: .alarm, message: "AlarmSound - unable to play sound; error: \(error)")
  87. }
  88. }
  89. static func play(repeating: Bool) {
  90. guard !isPlaying else {
  91. return
  92. }
  93. enableAudio()
  94. do {
  95. audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
  96. audioPlayer!.delegate = audioPlayerDelegate
  97. try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category(rawValue: convertFromAVAudioSessionCategory(AVAudioSession.Category.playback)))
  98. try AVAudioSession.sharedInstance().setActive(true)
  99. audioPlayer!.numberOfLoops = repeating ? -1 : 0
  100. // Store existing volume
  101. if systemOutputVolumeBeforeOverride == nil {
  102. systemOutputVolumeBeforeOverride = AVAudioSession.sharedInstance().outputVolume
  103. }
  104. if !audioPlayer!.prepareToPlay() {
  105. LogManager.shared.log(category: .alarm, message: "AlarmSound - audio player failed preparing to play")
  106. }
  107. if audioPlayer!.play() {
  108. if !isPlaying {
  109. LogManager.shared.log(category: .alarm, message: "AlarmSound - not playing after calling play")
  110. LogManager.shared.log(category: .alarm, message: "AlarmSound - rate value: \(audioPlayer!.rate)")
  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. }
  179. /* if an error occurs while decoding it will be reported to the delegate. */
  180. func audioPlayerDecodeErrorDidOccur(_: AVAudioPlayer, error: Error?) {
  181. if let error = error {
  182. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerDecodeErrorDidOccur: \(error)")
  183. } else {
  184. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerDecodeErrorDidOccur")
  185. }
  186. }
  187. /* AVAudioPlayer INTERRUPTION NOTIFICATIONS ARE DEPRECATED - Use AVAudioSession instead. */
  188. /* audioPlayerBeginInterruption: is called when the audio session has been interrupted while the player was playing. The player will have been paused. */
  189. func audioPlayerBeginInterruption(_: AVAudioPlayer) {
  190. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerBeginInterruption")
  191. }
  192. /* audioPlayerEndInterruption:withOptions: is called when the audio session interruption has ended and this player had been interrupted while playing. */
  193. /* Currently the only flag is AVAudioSessionInterruptionFlags_ShouldResume. */
  194. func audioPlayerEndInterruption(_: AVAudioPlayer, withOptions flags: Int) {
  195. LogManager.shared.log(category: .alarm, message: "AlarmRule - audioPlayerEndInterruption withOptions: \(flags)")
  196. }
  197. }
  198. // Helper function inserted by Swift 4.2 migrator.
  199. private func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String {
  200. return input.rawValue
  201. }
  202. extension MPVolumeView {
  203. static func setVolume(_ volume: Float) {
  204. // Need to use the MPVolumeView in order to change volume, but don't care about UI set so frame to .zero
  205. let volumeView = MPVolumeView(frame: .zero)
  206. // Search for the slider
  207. let slider = volumeView.subviews.first(where: { $0 is UISlider }) as? UISlider
  208. // Update the slider value with the desired volume.
  209. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.01) {
  210. slider?.value = volume
  211. }
  212. // Optional - Remove the HUD
  213. if let app = UIApplication.shared.delegate as? AppDelegate, let window = app.window {
  214. volumeView.alpha = 0.000001
  215. window.addSubview(volumeView)
  216. }
  217. }
  218. }