如何使用python更改Windows中的系统音量?

问题描述 投票:0回答:2

如何使用 python 更改 Windows 中的系统音量,just 使用 python 标准库? 我知道如何通过按音量键来更改系统音量:

from ctypes import WinDLL
user32 = WinDLL("user32")

# Turns volume up:
for _ in range(50):
    user32.keybd_event(0xAF, 0, 0, 0)
    user32.keybd_event(0xAF, 0, 2, 0)

# Turns volume down:
for _ in range(50):
    user32.keybd_event(0xAE, 0, 0, 0)
    user32.keybd_event(0xAE, 0, 2, 0)

但是如何在不使用任何额外的 python 包的情况下将音量设置为某个值? 我还想要一种获取当前音量的方法。

编辑:建议的问题没有回答我的问题,因为该问题的所有答案要么在 Windows 上不起作用,要么使用额外的 python 包,要么只是按音量键,而我想要将音量设置为某个值和获取当前音量的方法。

python windows ctypes volume
2个回答
1
投票

这可能对你有用:https://docs.python.org/3/library/ossaudiodev.html

尝试查看 oss_mixer_device.get 和 .set。我目前正在使用移动设备,但稍后我可以尝试为您提供一段工作代码。


-1
投票

我已经在 GitHub 上创建了一个用于设置音量的存储库。您可以将其用作导出,以便将其导入到您正在处理的任何内容中。

https://github.com/TerinalTech/pyvfw

注意:这使用了 pycaw、comtypes 和 ctypes,但它完全有效。

也许这应该是您正在寻找的功能:

def setVolume(vol=-1, max=100, force=False):
    """
    Sets the absolute volume for all apps.\n
    If the current volume is greater than `max`, current volume will be returned.\n
    `force` parameter, if True, forces all programs to be on the same volume as the master volume.
    `curvol` or `vol` always returns the master volume.
    Returns: `curvol` if `curvol > max`, else `vol` parameter, or nothing if vol or max < 0
    """
    try:
        devices = AudioUtilities.GetSpeakers() # Get the primary speaker
        interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None) # Do some activation
        volume = cast(interface, POINTER(IAudioEndpointVolume)) # Init the volume setters and getters
        curvol = float(round(volume.GetMasterVolumeLevelScalar() * 100)) # Get current volume in a range from 0-100, rounded.
        max = float(round(max))
        if vol < 0 or max <= 0: toggleMute(); return # Invalid cases
        if curvol > max: return curvol # Return curvol if it is greater than max
        volume.SetMasterVolumeLevelScalar(vol/100, None) # Set the master volume, in a range from 0-1
        if force: alignSounds()
        return vol
    except Exception as e: print(f"An error occured trying to setVolume: {e}")

alignSounds
功能使所有应用程序音量与主音量相同 - 如果您熟悉音量混合器。

def alignSounds():
    """
    Makes all apps' sound levels to that of the master volume.\n
    Returns True or False if operations succeded.
    """
    try:
        sessions = AudioUtilities.GetAllSessions()
        for session in sessions: # Loop through every application
            if session.Process: # To avoid NoneType Error
                volume = session._ctl.QueryInterface(ISimpleAudioVolume) # Init the volume object (this is different from the one taken from the cast() method)
                volume.SetMasterVolume(1, None) # Set the relative volume to 100% to make it equal to the master volume
        return True
    except: return False
© www.soinside.com 2019 - 2024. All rights reserved.