0

A gentleman asked this question 9 months ago. It was never answered correctly and the thread was closed. He was told to do this:

On Windows, use pycaw:

from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))

volume.GetMasterVolumeLevelScalar()

And with this, the thread was closed but this is NOT the answer, this scalar level is NOT the 0-100level of master volume displayed on a PC monitor in the systray. I have pycaw and comtypes installed and am on the current python 3.11.1. I have entered all the above commands into my python. Please may I know what command to use to get the exact output of my master volume. If my pc volume is 50 I want an output of 50. With the above instructions, at pc volume level 100, the scalar level output is 1. Thats worthless to me. Please help.

I tried using the command

volume.GetMasterVolume()

hoping to get the master level return. instead I got an error:

>>> volume.GetMasterVolume()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'POINTER(IAudioEndpointVolume)' object has no attribute 'GetMasterVolume'. Did      you mean: 'GetMasterVolumeLevel'?

So I tried volume.GetMasterVolumeLevel() and at 100 master volume this returned 0.0 again worthless.

Why does volume.GetMasterVolume() not work? What do I have to do to make it work?

youngson
  • 85
  • 10
  • 2
    Have you looked at the documentation? https://learn.microsoft.com/en-us/windows/win32/api/endpointvolume/nn-endpointvolume-iaudioendpointvolume `GetMasterVolumeLevelScalar` returns a float from 0 to 1. If you thought you were at 100%, then the 1.0 is exactly what you want. – Tim Roberts May 07 '23 at 06:05
  • Which question are you referring to? It would be useful to know that. – Gert Arnold May 07 '23 at 14:55

1 Answers1

1

After running the code myself, I see that the code you have provided does actually work as you want. The difference, however, is that volume is a number between 0 and 1, instead of 0 and 100.

All you need is a simple change:

from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))

vol = volume.GetMasterVolumeLevelScalar() * 100
vol_str = f"{vol:.0f}%"
print(vol_str)

This prints the volume as an integer percentage. If you want a different number/display format, modify vol_str as needed.

See also:

youngson
  • 85
  • 10