BackgroundTaskAudio.swift 2.2 KB

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