BackgroundTaskAudio.swift 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // LoopFollow
  2. // BackgroundTaskAudio.swift
  3. import AVFoundation
  4. class BackgroundTask {
  5. // MARK: - Vars
  6. var player = AVAudioPlayer()
  7. var timer = Timer()
  8. // MARK: - Methods
  9. func startBackgroundTask() {
  10. NotificationCenter.default.addObserver(self, selector: #selector(interruptedAudio), name: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance())
  11. playAudio()
  12. }
  13. func stopBackgroundTask() {
  14. NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: nil)
  15. player.stop()
  16. LogManager.shared.log(category: .general, message: "Silent audio stopped", isDebug: true)
  17. }
  18. @objc fileprivate func interruptedAudio(_ notification: Notification) {
  19. LogManager.shared.log(category: .general, message: "Silent audio interrupted")
  20. if notification.name == AVAudioSession.interruptionNotification, notification.userInfo != nil {
  21. var info = notification.userInfo!
  22. var intValue = 0
  23. (info[AVAudioSessionInterruptionTypeKey]! as AnyObject).getValue(&intValue)
  24. if intValue == 1 { playAudio() }
  25. }
  26. }
  27. fileprivate func playAudio() {
  28. do {
  29. let bundle = Bundle.main.path(forResource: "blank", ofType: "wav")
  30. let alertSound = URL(fileURLWithPath: bundle!)
  31. // try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
  32. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .mixWithOthers)
  33. try AVAudioSession.sharedInstance().setActive(true)
  34. try player = AVAudioPlayer(contentsOf: alertSound)
  35. // Play audio forever by setting num of loops to -1
  36. player.numberOfLoops = -1
  37. player.volume = 0.01
  38. player.prepareToPlay()
  39. player.play()
  40. LogManager.shared.log(category: .general, message: "Silent audio playing", isDebug: true)
  41. } catch {
  42. LogManager.shared.log(category: .general, message: "playAudio, error: \(error)")
  43. }
  44. }
  45. }