Set system volume via script/KM variable

I use this macro to store the current system volume in a KM variable:

My question: How can I use the KM variable (VOLUMESTATE) to set a new volume state?

The command is:

set volume output volume xx --100% # xx=volume state

What is the best way to use $KMVAR_VOLUMESTATE (in my case) in oascript or rather bash scripts?

Example: osascript -e "set volume output volume $KMVAR_VOLUMESTATE --100%"

TIA, Thomas

Hey Thomas,

Examples of Set/Get KM-Variables with AppleScript:

set currentOutputVolume to output volume of (get volume settings)

tell application "Keyboard Maestro Engine"
  try
    set value of variable "currentOutputVolume" to currentOutputVolume
  on error
    make new variable with properties {name:"currentOutputVolume", value:currentOutputVolume}
    set value of variable "currentOutputVolume" to currentOutputVolume
  end try
end tell

tell application "Keyboard Maestro Engine"
  set value of variable "currentOutputVolume" to 75
end tell

tell application "Keyboard Maestro Engine"
  set currentOutputVolume to value of variable "currentOutputVolume"
end tell

set volume output volume currentOutputVolume

An Execute Shell Script Action from Keyboard Maestro:

osascript -e "set volume output volume $KMVAR_currentOutputVolume"

Does this sufficiently answer your question?

I never run AppleScript from the shell unless it’s specifically to my advantage to do so. Anything I use regularly I run from a compiled AppleScript, because they run a little bit faster.

Keyboard Maestro uses osascript to run AppleScripts, so unless you need it to run as part of a larger shell-script it’s generally better to run straight AppleScript in my opinion. But your milage may vary.


Best Regards,
Chris

1 Like

I can certainly understand Chris's preference for compiled scripts, but FWIW, from the Javascript perspective, there may be a couple of general advantages to using a shell script:

  1. KM_VAR values are easily read in the shell
  2. If you are writing reusable code (text etc) you can use a javascript module pattern to keep the KM part separate from the rest of the code, in case you want to use your .js on iOS or elsewhere.

( but 2 is probably not relevant here : - )

#!/bin/bash
osascript -l JavaScript <<JXA_END 2>/dev/null
(function (v) {
	var a = Application.currentApplication();
	a.includeStandardAdditions = true;
	a.setVolume(null, {
		outputVolume: v
	});
})($KMVAR_VOLUMESTATE);
JXA_END

Rob