ClickAudio.swift 1.6 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import AVFAudio
  2. import Foundation
  3. @MainActor final class ClickAudio {
  4. enum Kind: String, CaseIterable { case button = "tap-button", number = "tap-number" }
  5. static let shared = ClickAudio()
  6. nonisolated static let preferenceKey = PlayerPreferenceKeys.sound
  7. private var players: [Kind: [AVAudioPlayer]] = [:]
  8. private var configured = false
  9. func play(_ kind: Kind = .button) {
  10. let defaults = UserDefaults.standard
  11. guard defaults.object(forKey: Self.preferenceKey) == nil || defaults.bool(forKey: Self.preferenceKey) else { return }
  12. if !configured {
  13. do {
  14. // Ambient respects the silent switch and mixes with the player's other audio.
  15. try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default)
  16. configured = true
  17. } catch { return }
  18. }
  19. if players[kind] == nil {
  20. guard let url = Bundle.main.url(forResource: kind.rawValue, withExtension: "wav", subdirectory: "Audio")
  21. ?? Bundle.main.url(forResource: kind.rawValue, withExtension: "wav") else { return }
  22. players[kind] = (0..<3).compactMap { _ in
  23. guard let player = try? AVAudioPlayer(contentsOf: url) else { return nil }
  24. player.volume = kind == .number ? 0.40 : 0.50
  25. player.prepareToPlay()
  26. return player
  27. }
  28. }
  29. guard let pool = players[kind], let player = pool.first(where: { !$0.isPlaying }) ?? pool.first else { return }
  30. player.currentTime = 0
  31. player.play()
  32. }
  33. }