In this post, I will introduce a python package, osascript
that allows us to control the sound volume easily.
andrewpetrochenkov / osascript.py
đ đ osascript (AppleScript) python implementation
Installation
$ [sudo] pip install osascript
Examples
>>> import osascript
>>> code,out,err = osascript.run('display dialog "42"')
Links
If you prefer to use nodejs, I recommend you check this out.
https://github.com/mikaelbr/node-osascript
If you are a Windows user, I recommend you to try pycaw
https://github.com/AndreMiras/pycaw
What we can do with osascript
is to set volume and get volume information without writing AppleScript.
AppleScript
AppleScript is a scripting language created by Apple. It allows users to directly control scriptable Macintosh applications, as well as parts of macOS itself. You can create scriptsâsets of written instructionsâto automate repetitive tasks, combine features from multiple scriptable applications, and create complex workflows.
AppleScript is promising when we want to do control macOS's functionalities, but personally, I don't really like to write it lol.
Install
$ pip install osascript
Set volume
import osascript
target_volume = 50
vol = "set volume output volume " + str(50)
osascript.osascript(vol)
# or
target_volume = 50
osascript.osascript("set volume output volume {}".format(target_volume))
# or
osascript.osascript("set volume output volume 50")
Get volume info
The return format is and what we need is output volume
to know the current sound volume.
(0, 'output volume:50, input volume:58, alert volume:100, output muted:false', '')
The way to get the current volume is straightforward.
Get the volume settings via osascript
and parse the tuple.
result = osascript.osascript('get volume settings')
print(result)
print(type(result))
volInfo = result[1].split(',')
outputVol = volInfo[0].replace('output volume:', '')
print(outputVol)
The result is 50
.
Top comments (0)