2

I need to see when the sound volume on my Mac hits a certain point, in Python (and preferably without the need of any permissions). Any pointers appreciated.

nohillside
  • 100,768

1 Answers1

1

You have a couple of approaches you can use here.

AppleScript via osascript CLI

You can use AppleScript directly via the osascript CLI to get and set the volume like so:

Get volume - Echos a number from 0 to 100

$ osascript -e 'output volume of (get volume settings)'

Set volume - Where 50 is a number from 0 to 100

$ osascript -e 'set volume output volume 50'

Get mute state - Echos a string of 'true' or 'false'

$ osascript -e 'output muted of (get volume settings)'

Set mute state - Where 'true' can be 'true' or 'false'

$ osascript -e 'set volume output muted true'

Using osascript module in Python

If you have Python3 installed and Xcode you can install the osascript module like so:

Install Xcode

$ xcode-select --install

Install virtualenv

$ pip3 install virtualenv

Create a Virtualenv project, and activate it

$ virtualenv venv
$ . venv/bin/activate

Now within this custom Virtualenv environment, install Python module

$ pip3 install osascript
Collecting osascript
Collecting public (from osascript)
Collecting runcmd (from osascript)
Requirement already satisfied: setuptools in ./venv/lib/python3.7/site-packages (from osascript) (41.0.1)
Collecting temp (from osascript)
Collecting psutil (from runcmd->osascript)
Installing collected packages: public, psutil, runcmd, temp, osascript
Successfully installed osascript-2019.4.13 psutil-5.6.1 public-2019.4.13 runcmd-2019.4.13 temp-2019.4.13

Here's an example Python program that will set the volume to 100

$ cat vol.py
#!/usr/bin/env python3

import osascript

osascript.run("set volume output volume 100")
code, out, err = osascript.run("output volume of (get volume settings)")
print(out)

Running this will set to 100 and then display the volume's level

$ ./vol.py
100

References

Miro
  • 3
slm
  • 4,798