aboutsummaryrefslogtreecommitdiff
path: root/Hotline/Library
diff options
context:
space:
mode:
authorDustin Mierau <dustin@mierau.me>2025-11-08 17:21:54 -0800
committerDustin Mierau <dustin@mierau.me>2025-11-08 17:21:54 -0800
commit206e4bbdaba85062a38b32c16a9937ab42cddb47 (patch)
tree3473090eb3ede734095bbc30670e2ccd962e7181 /Hotline/Library
parent2112b181aa654fc9d05770d09aa0cd098cd76bc9 (diff)
Improve sound effect management and use NSSound on macOS.
Diffstat (limited to 'Hotline/Library')
-rw-r--r--Hotline/Library/SoundEffects.swift51
1 files changed, 21 insertions, 30 deletions
diff --git a/Hotline/Library/SoundEffects.swift b/Hotline/Library/SoundEffects.swift
index 93f8b9a..4964b94 100644
--- a/Hotline/Library/SoundEffects.swift
+++ b/Hotline/Library/SoundEffects.swift
@@ -1,7 +1,7 @@
import Foundation
-import AVFAudio
+import AppKit
-enum SoundEffects: String {
+enum SoundEffect: String {
case loggedIn = "logged-in"
case chatMessage = "chat-message"
case transferComplete = "transfer-complete"
@@ -10,41 +10,32 @@ enum SoundEffects: String {
case newNews = "new-news"
case serverMessage = "server-message"
case error = "error"
+
+ static var all: [SoundEffect] = [.loggedIn, .chatMessage, .transferComplete, .userLogin, .userLogout, .newNews, .serverMessage, .error]
}
@Observable
-class SoundEffectPlayer: NSObject, AVAudioPlayerDelegate {
- static let shared = SoundEffectPlayer()
+class SoundEffects {
+ static let shared = SoundEffects()
- private var activeSounds: [AVAudioPlayer] = []
+ private var preloadedSounds: [SoundEffect: NSSound] = [:]
- 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)
+ private init() {
+ // Preload sound effects
+ for effect in SoundEffect.all {
+ if let soundFileURL = Bundle.main.url(forResource: effect.rawValue, withExtension: "aiff"),
+ let sound = NSSound(contentsOf: soundFileURL, byReference: true) {
+ sound.volume = 0.75
+ self.preloadedSounds[effect] = sound
}
}
}
-
- func audioPlayerDidFinishPlaying(_ player: AVAudioPlayer, successfully flag: Bool) {
- if let i = self.activeSounds.firstIndex(of: player) {
- self.activeSounds.remove(at: i)
- }
+
+ static func play(_ name: SoundEffect) {
+ Self.shared.play(name)
+ }
+
+ func play(_ name: SoundEffect) {
+ self.preloadedSounds[name]?.play()
}
}