AudioPlayerManager.swift 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. //
  2. // AudioPlayerManager.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2020/6/17.
  6. // Copyright © 2020 zoneland. All rights reserved.
  7. //
  8. import AVFoundation
  9. import CocoaLumberjack
  10. protocol AudioPlayerManagerDelegate {
  11. func didAudioPlayerBeginPlay(_ AudioPlayer: AVAudioPlayer)
  12. func didAudioPlayerStopPlay(_ AudioPlayer: AVAudioPlayer)
  13. func didAudioPlayerPausePlay(_ AudioPlayer: AVAudioPlayer)
  14. }
  15. class AudioPlayerManager: NSObject {
  16. static let shared: AudioPlayerManager = {
  17. return AudioPlayerManager()
  18. }()
  19. private override init() {
  20. super.init()
  21. DDLogDebug("初始化播放工具类")
  22. self.stopFloatingBtn = O2AudioPlayFloatingWindow(frame: CGRect(x: kScreenW - 60, y: 120, width: 60, height: 60 ))
  23. self.stopFloatingBtn?.hideFloatingBtn()
  24. }
  25. var delegate: AudioPlayerManagerDelegate?
  26. var player: AVAudioPlayer!
  27. // 悬浮的关闭音频按钮
  28. var stopFloatingBtn: O2AudioPlayFloatingWindow?
  29. func managerAudioWithData(_ data:Data, toplay:Bool) {
  30. if toplay {
  31. playAudioWithData(data)
  32. } else {
  33. pausePlayingAudio()
  34. }
  35. }
  36. func playAudioWithData(_ voiceData:Data) {
  37. do {
  38. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .defaultToSpeaker)
  39. } catch let error as NSError {
  40. print("set category fail \(error)")
  41. }
  42. if player != nil {
  43. player.stop()
  44. player = nil
  45. }
  46. do {
  47. let pl: AVAudioPlayer = try AVAudioPlayer(data: voiceData)
  48. pl.delegate = self
  49. pl.play()
  50. player = pl
  51. } catch let error as NSError {
  52. print("alloc AVAudioPlayer with voice data fail with error \(error)")
  53. }
  54. UIDevice.current.isProximityMonitoringEnabled = true
  55. //显示关闭按钮
  56. self.stopFloatingBtn?.showFloatingBtn()
  57. }
  58. func pausePlayingAudio() {
  59. player?.pause()
  60. }
  61. func stopAudio() {
  62. if player != nil && player.isPlaying {
  63. player.stop()
  64. }
  65. UIDevice.current.isProximityMonitoringEnabled = false
  66. delegate?.didAudioPlayerStopPlay(player)
  67. // 隐藏关闭按钮
  68. self.stopFloatingBtn?.hideFloatingBtn()
  69. }
  70. }
  71. extension AudioPlayerManager: AVAudioPlayerDelegate {
  72. func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
  73. stopAudio()
  74. }
  75. }