IceCubes/Packages/Env/Sources/Env/SoundEffectManager.swift

46 lines
1.1 KiB
Swift
Raw Normal View History

2023-09-16 14:15:03 +02:00
import AudioToolbox
2023-03-13 13:38:28 +01:00
import AVKit
2023-02-28 18:55:08 +01:00
import CoreHaptics
import UIKit
@MainActor
2023-02-28 18:55:08 +01:00
public class SoundEffectManager {
public static let shared: SoundEffectManager = .init()
2023-09-16 14:15:03 +02:00
public enum SoundEffect: String, CaseIterable {
case pull, refresh, tootSent, tabSelection, bookmark, boost, favorite, share
2023-02-28 18:55:08 +01:00
}
2023-09-16 14:15:03 +02:00
private var systemSoundIDs: [SoundEffect: SystemSoundID] = [:]
2023-09-16 14:15:03 +02:00
2023-02-28 18:55:08 +01:00
private let userPreferences = UserPreferences.shared
2023-09-16 14:15:03 +02:00
private init() {
registerSounds()
}
2023-03-13 13:38:28 +01:00
private func registerSounds() {
SoundEffect.allCases.forEach { effect in
guard let url = Bundle.main.url(forResource: effect.rawValue, withExtension: "wav") else { return }
register(url: url, for: effect)
}
}
2023-09-16 14:15:03 +02:00
private func register(url: URL, for effect: SoundEffect) {
var soundId: SystemSoundID = .init()
AudioServicesCreateSystemSoundID(url as CFURL, &soundId)
systemSoundIDs[effect] = soundId
}
public func playSound(_ effect: SoundEffect) {
guard
userPreferences.soundEffectEnabled,
let soundId = systemSoundIDs[effect]
else {
return
2023-02-28 18:55:08 +01:00
}
AudioServicesPlaySystemSound(soundId)
2023-02-28 18:55:08 +01:00
}
}