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.

1
  • When posting coding questions, please share what you already have, and/or have tried to solve the problem.
    – nohillside
    Commented Apr 28, 2019 at 10:11

1 Answer 1

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .