M
M
Maxim Belozerov2021-03-19 17:09:01
Python
Maxim Belozerov, 2021-03-19 17:09:01

How to change computer volume via python?

Good day! I am creating a program related to a telegram bot and changing the sound on windows. On the Internet, I found and mounted only the following code:

def set_volume(massege, param):
    try:
        from ctypes import cast, POINTER
        from comtypes import CLSCTX_ALL
        from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
        # ----------------------------------------------------------------------------------------------------------------------
        if param == 0:
            vol = 89.9
        elif param == 10:
            vol = 35
        elif param == 20:
            vol = 24
        elif param == 30:
            vol = 18
        elif param == 40:
            vol = 14
        elif param == 50:
            vol = 10.5
        elif param == 60:
            vol = 7
        elif param == 70:
            vol = 4.5
        elif param == 80:
            vol = 2
        elif param == 90:
            vol = 1.5
        elif param == 100:
            vol = 0
        # ----------------------------------------------------------------------------------------------------------------------
        devices = AudioUtilities.GetSpeakers()
        interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
        volume = cast(interface, POINTER(IAudioEndpointVolume))
        volume.GetMute()
        volume.GetMasterVolumeLevel()
        volume.GetVolumeRange()
        volume.SetMasterVolumeLevel(-vol, None)
    except:
        write_message(massege, "Непредвиденная ошибка!")

But it sometimes throws errors related to the library. Is it possible to change this part of the code or somehow fix it?
Mistake:

Exception ignored in: <function _compointer_base.__del__ at 0x00000000037E64C0>
Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\__init__.py", line 912, in __del__
    self.Release()
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\comtypes\__init__.py", line 1166, in Release
    return self.__com_Release()
OSError: exception: access violation writing 0x0000000000000000

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alex F, 2021-03-19
@delvin-fil

Umm... Dear!
Like this:

elif param == 100:
            vol = 0

don't do it!
Do It:
elif param == 100:
            vol = 0.1

A
Alexander, 2021-03-21
@Survtur

If the error is given SOMETIMES, and it is not clear why, then maybe wrap it in try... exceptand try several times?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question