DEV Community

loading...

Control mac Sound Volume By Python

kojikanao profile image Koji (he/him) ・2 min read

In this post, I will introduce a python package, osascript that allows us to control the sound volume easily.

GitHub logo andrewp-as-is / osascript.py

🍎 🐍 osascript (AppleScript) python implementation

Installation

$ [sudo] pip install osascript
Enter fullscreen mode Exit fullscreen mode

Examples

>>> import osascript

>>> code,out,err = osascript.run('display dialog "42"')
Enter fullscreen mode Exit fullscreen mode

Links

readme42.com






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.

https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html

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
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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', '')
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

The result is 50.

Discussion (0)

Forem Open with the Forem app