LNIMAudioCallBellPlayer.swift 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. //
  2. // LNIMAudioCallBellPlayer.swift
  3. // Gami
  4. //
  5. // Created by OneeChan on 2026/2/9.
  6. //
  7. import Foundation
  8. import AVFAudio
  9. class LNIMAudioCallBellPlayer: NSObject {
  10. private var player: AVAudioPlayer?
  11. private var playing = false
  12. func startPlay(isInCome: Bool) {
  13. if player != nil {
  14. stop()
  15. }
  16. let path = if isInCome {
  17. Bundle.main.path(forResource: "phone_bell", ofType: "mp3")
  18. } else {
  19. Bundle.main.path(forResource: "phone_bell", ofType: "mp3")
  20. }
  21. guard let path else { return }
  22. do {
  23. player = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
  24. } catch let error as NSError {
  25. print("Error: \(error.localizedDescription)")
  26. return
  27. }
  28. guard let prepare = player?.prepareToPlay(), prepare else {
  29. return
  30. }
  31. playing = true
  32. player?.delegate = self
  33. player?.play()
  34. }
  35. func stop() {
  36. playing = false
  37. player?.stop()
  38. player = nil
  39. }
  40. }
  41. extension LNIMAudioCallBellPlayer: AVAudioPlayerDelegate {
  42. func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
  43. if playing {
  44. player.play()
  45. }
  46. }
  47. }