aboutsummaryrefslogtreecommitdiff
path: root/Hotline/Utility/SoundEffects.swift
blob: 629af712b3f80a371878ecb8ef7640e1d95aeff5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import Foundation
import AVFAudio

enum SoundEffects: String {
  case loggedIn = "logged-in"
  case chatMessage = "chat-message"
  case transferComplete = "transfer-complete"
  case userLogin = "user-login"
  case userLogout = "user-logout"
  case newNews = "new-news"
  case serverMessage = "server-message"
}

@Observable
class SoundEffectPlayer: NSObject, AVAudioPlayerDelegate {
  static let shared = SoundEffectPlayer()
  
  private var activeSounds: [AVAudioPlayer] = []
  
  func playSoundEffect(_ name: SoundEffects) {
    // Load a local sound file
    guard let soundFileURL = Bundle.main.url(
      forResource: name.rawValue,
      withExtension: "aiff"
    ) else {
      return
    }
    
    DispatchQueue.main.async { [weak self] in
      guard let self = self else {
        return
      }
      
      if let soundEffect = try? AVAudioPlayer(contentsOf: soundFileURL) {
        soundEffect.delegate = self
        soundEffect.volume = 0.75
        soundEffect.play()
        
        self.activeSounds.append(soundEffect)
      }
    }
  }

  func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    if let i = self.activeSounds.firstIndex(of: player) {
      self.activeSounds.remove(at: i)
    }
  }
}