Fix mute/unmute race condition

This commit is contained in:
Beingpax 2025-07-25 11:23:09 +05:45
parent a0008de55d
commit c9805d295e

View File

@ -9,6 +9,7 @@ class MediaController: ObservableObject {
static let shared = MediaController()
private var didMuteAudio = false
private var wasAudioMutedBeforeRecording = false
private var currentMuteTask: Task<Bool, Never>?
@Published var isSystemMuteEnabled: Bool = UserDefaults.standard.bool(forKey: "isSystemMuteEnabled") {
didSet {
@ -49,6 +50,10 @@ class MediaController: ObservableObject {
func muteSystemAudio() async -> Bool {
guard isSystemMuteEnabled else { return false }
// Cancel any existing mute task and create a new one
currentMuteTask?.cancel()
let task = Task<Bool, Never> {
// First check if audio is already muted
wasAudioMutedBeforeRecording = isSystemAudioMuted()
@ -63,16 +68,26 @@ class MediaController: ObservableObject {
return success
}
currentMuteTask = task
return await task.value
}
/// Restores system audio after recording
func unmuteSystemAudio() async {
guard isSystemMuteEnabled else { return }
// Wait for any pending mute operation to complete first
if let muteTask = currentMuteTask {
_ = await muteTask.value
}
// Only unmute if we actually muted it (and it wasn't already muted)
if didMuteAudio && !wasAudioMutedBeforeRecording {
_ = executeAppleScript(command: "set volume without output muted")
}
didMuteAudio = false
currentMuteTask = nil
}
/// Executes an AppleScript command