Home > Back-end >  Unable to mute and unmute mic using applescript
Unable to mute and unmute mic using applescript

Time:03-10

I am working on a script to turn on/off mic on macOS

if input volume of (get volume settings) is 0 then
    if storedInputLevel exists then
        set volume input volume storedInputLevel
        log "unmute it"
    end if
else
    tell application "System Events"
        -- save the current input volume setting --
        set storedInputLevel to input volume of (get volume settings)
    end tell
    set volume input volume 0
    log "mute it"
end if

The above script works only when the initial state of mic volume is > 0 otherwise it throws error "storedInputLevel" doesn't exists.

The purpose of storedInputLevel is assign the mic volume that user used to configure. My goal is to toggle mic volume on/off.

Any help is appreciated

CodePudding user response:

In the first line you are asking for a variable which doesn't exist. exists cannot be used on variable names, it can only be used on properties or elements.

Basically you need a place to store a value permanently.

In the past you could do that simply with a property. But since scripts can be code-signed and modifying a property breaks the signature it's not reliable anymore.

An alternative is to store the value in user defaults. The value is stored in a property list file ~/Library/Preferences/com.myself.muteinput.plist

Change com.myself.muteinput to whatever you like. System Events is not needed.

try
    set storedInputLevel to (do shell script "defaults read com.myself.muteinput value") as integer
on error
    set storedInputLevel to 0
end try

if input volume of (get volume settings) is 0 then
    set volume input volume storedInputLevel
    log "unmute it"
else
    set storedInputLevel to input volume of (get volume settings)
    do shell script "defaults write com.myself.muteinput value -int " & (storedInputLevel as text)
    set volume input volume 0
    log "mute it"
end if
  • Related