| 1234567891011121314151617181920212223242526272829303132333435 |
- import AVFAudio
- import Foundation
- @MainActor final class ClickAudio {
- enum Kind: String, CaseIterable { case button = "tap-button", number = "tap-number" }
- static let shared = ClickAudio()
- nonisolated static let preferenceKey = PlayerPreferenceKeys.sound
- private var players: [Kind: [AVAudioPlayer]] = [:]
- private var configured = false
- func play(_ kind: Kind = .button) {
- let defaults = UserDefaults.standard
- guard defaults.object(forKey: Self.preferenceKey) == nil || defaults.bool(forKey: Self.preferenceKey) else { return }
- if !configured {
- do {
- // Ambient respects the silent switch and mixes with the player's other audio.
- try AVAudioSession.sharedInstance().setCategory(.ambient, mode: .default)
- configured = true
- } catch { return }
- }
- if players[kind] == nil {
- guard let url = Bundle.main.url(forResource: kind.rawValue, withExtension: "wav", subdirectory: "Audio")
- ?? Bundle.main.url(forResource: kind.rawValue, withExtension: "wav") else { return }
- players[kind] = (0..<3).compactMap { _ in
- guard let player = try? AVAudioPlayer(contentsOf: url) else { return nil }
- player.volume = kind == .number ? 0.40 : 0.50
- player.prepareToPlay()
- return player
- }
- }
- guard let pool = players[kind], let player = pool.first(where: { !$0.isPlaying }) ?? pool.first else { return }
- player.currentTime = 0
- player.play()
- }
- }
|