Last active
March 5, 2021 01:35
-
-
Save amarcu5/b7eb33b8b2ac58378f2e16d9ec7ad4e2 to your computer and use it in GitHub Desktop.
Small macOS utility to ensure system is muted when asleep to prevent potential sounds during Power Nap; Addresses reddit issue: https://www.reddit.com/r/apple/comments/8t041u/my_macbook_creeps_me_out_by_starting_to_talk_in/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// MuteOnSleep | |
// Ensures system is muted when asleep to prevent potential sounds during Power Nap | |
// | |
// Install by pasting the following in a terminal prompt: | |
// curl https://s3.amazonaws.com/muteonsleep-tool/muteonsleep.tar.gz | tar xvz -C /usr/local/bin/; osascript -e 'tell application "System Events" to make login item at end with properties {path:"/usr/local/bin/muteonsleep", hidden:true}'; nohup /usr/local/bin/muteonsleep & | |
// | |
// Uninstall with: | |
// pkill muteonsleep; osascript -e 'tell application "System Events" to delete login item "muteonsleep"'; rm /usr/local/bin/muteonsleep | |
// | |
import Foundation | |
import AppKit | |
@discardableResult func executeAppleScript(source: String) -> String { | |
let process = Process() | |
process.launchPath = "/usr/bin/osascript" | |
process.arguments = [String(format: "-e %@", source)] | |
let pipe = Pipe() | |
process.standardOutput = pipe | |
process.launch() | |
let data = pipe.fileHandleForReading.readDataToEndOfFile() | |
guard let output = String(data: data, encoding: .utf8) else { | |
return "" | |
} | |
return output.trimmingCharacters(in: .whitespacesAndNewlines) | |
} | |
func isMuted() -> Bool { | |
return executeAppleScript(source: "output muted of (get volume settings)") == "true" | |
} | |
func mute() { | |
executeAppleScript(source: "set volume with output muted") | |
} | |
func unmute() { | |
executeAppleScript(source: "set volume without output muted") | |
} | |
var alreadyMutedBeforeSleep = false | |
let notificationCenter = NSWorkspace.shared.notificationCenter | |
notificationCenter.addObserver(forName: NSWorkspace.willSleepNotification, | |
object: nil, | |
queue: nil, | |
using: { _ in | |
alreadyMutedBeforeSleep = isMuted() | |
if !alreadyMutedBeforeSleep { | |
mute() | |
} | |
}) | |
notificationCenter.addObserver(forName: NSWorkspace.didWakeNotification, | |
object: nil, | |
queue: nil, | |
using: { _ in | |
if !alreadyMutedBeforeSleep { | |
unmute() | |
} | |
}) | |
RunLoop.current.run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment