In our previous post we showed how to set the Windows audio volume using pycaw.
First, we install the library using
pip install pycaw
Note: pycaw does not work with WSL (Windows Subsystem for Linux)! You actually need to install it using a Python environment running on Windows. I recommend Anaconda.
In order to set the audio balance, we can use volume.SetChannelVolumeLevel(...)
:
from ctypes import cast, POINTER from comtypes import CLSCTX_ALL from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume import math # Get default audio device using PyCAW devices = AudioUtilities.GetSpeakers() interface = devices.Activate( IAudioEndpointVolume._iid_, CLSCTX_ALL, None) volume = cast(interface, POINTER(IAudioEndpointVolume)) # Get current volume of the left channel currentVolumeLeft = volume.GetChannelVolumeLevel(0) # Set the volume of the right channel to half of the volume of the left channel volume.SetChannelVolumeLevel(1, currentVolumeLeft - 6.0, None) # NOTE: -6.0 dB = half volume !
Note that by convention, the left channel is channel 0 and the right channel is channel 1. Depending on the type of sound card, there might be as few as 1 channel (e.g. a mono headset) or many channels like in a multichannel USB audio interface. use volume.GetChannelCount()
to get the number of channels.