aboutsummaryrefslogtreecommitdiff
path: root/Hotline/Utility/SoundEffects.swift
blob: 426bfa23f3e19b8863c83851feceeda198374f45 (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
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"
}

@Observable
class SoundEffectPlayer: NSObject, AVAudioPlayerDelegate {
  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
    }
    
    do {
      let soundEffect = try AVAudioPlayer(contentsOf: soundFileURL)
      soundEffect.delegate = self
      
      self.activeSounds.append(soundEffect)
      
      soundEffect.volume = 0.75
      soundEffect.play()
    }
    catch {}
  }
  
  func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
    if let i = self.activeSounds.firstIndex(of: player) {
      self.activeSounds.remove(at: i)
    }
  }
}