AudioPlayerManager.swift 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. protocol AudioPlayerManagerDelegate {
  10. func didAudioPlayerBeginPlay(_ AudioPlayer: AVAudioPlayer)
  11. func didAudioPlayerStopPlay(_ AudioPlayer: AVAudioPlayer)
  12. func didAudioPlayerPausePlay(_ AudioPlayer: AVAudioPlayer)
  13. }
  14. class AudioPlayerManager: NSObject {
  15. static let shared: AudioPlayerManager = {
  16. return AudioPlayerManager()
  17. }()
  18. private override init() {super.init()}
  19. var delegate: AudioPlayerManagerDelegate?
  20. var player: AVAudioPlayer!
  21. func managerAudioWithData(_ data:Data, toplay:Bool) {
  22. if toplay {
  23. playAudioWithData(data)
  24. } else {
  25. pausePlayingAudio()
  26. }
  27. }
  28. func playAudioWithData(_ voiceData:Data) {
  29. do {
  30. try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: .defaultToSpeaker)
  31. } catch let error as NSError {
  32. print("set category fail \(error)")
  33. }
  34. if player != nil {
  35. player.stop()
  36. player = nil
  37. }
  38. do {
  39. let pl: AVAudioPlayer = try AVAudioPlayer(data: voiceData)
  40. pl.delegate = self
  41. pl.play()
  42. player = pl
  43. } catch let error as NSError {
  44. print("alloc AVAudioPlayer with voice data fail with error \(error)")
  45. }
  46. UIDevice.current.isProximityMonitoringEnabled = true
  47. }
  48. func pausePlayingAudio() {
  49. player?.pause()
  50. }
  51. func stopAudio() {
  52. if player != nil && player.isPlaying {
  53. player.stop()
  54. }
  55. UIDevice.current.isProximityMonitoringEnabled = false
  56. delegate?.didAudioPlayerStopPlay(player)
  57. }
  58. }
  59. extension AudioPlayerManager: AVAudioPlayerDelegate {
  60. func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
  61. stopAudio()
  62. }
  63. }