如何使用 Python 自动将 Windows 音频平衡设置为特定的 L-R 差异

当你无法将扬声器放置在离耳朵同等距离时,你需要调整音频平衡以补偿感知的音量差异。

Windows 允许你使用系统设置原生补偿音量 - 但它有一个关键问题:如果你将音量设置为零,你的平衡设置会丢失,你需要点击大量对话框才能重新配置。

在我们的上一篇文章如何使用 Python 设置 Windows 音频平衡中,我们展示了如何使用 pycaw 库(安装说明请参见该文章等)。

以下 Python 脚本可以运行以设置音频平衡。它被设计为在调整音量时保持以 dB 为单位的平均(即 L+R)音频电平(即它不会改变整体音量,从而避免震破你的耳膜),并且如果平衡已经在 0.1 dB 范围内,则不会进行任何调整。

desiredDelta 设置为你想要的左右差异(以 dB 为单位)(正值表示左扬声器将比右扬声器更响)!

auto_set_audio_balance.py
from ctypes import cast, POINTER
from comtypes import CLSCTX_ALL
from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume
import math

# 使用 PyCAW 获取默认音频设备
devices = AudioUtilities.GetSpeakers()
interface = devices.Activate(
    IAudioEndpointVolume._iid_, CLSCTX_ALL, None)
volume = cast(interface, POINTER(IAudioEndpointVolume))

# 获取左声道的当前音量
currentVolumeLeft = volume.GetChannelVolumeLevel(0)
# 将右声道的音量设置为左声道音量的一半
volumeL = volume.GetChannelVolumeLevel(0)
volumeR = volume.GetChannelVolumeLevel(1)
print(f"Before adjustment: L={volumeL:.2f} dB, R={volumeR:.2f} dB")

desiredDelta = 6.0 # L 和 R 之间的所需差异。正值表示 L 更响!

delta = abs(volumeR - volumeL)
mean = (volumeL + volumeR) / 2.

# 如果差异不是则重新配置平衡
if abs(delta - desiredDelta) > 0.1:
    # 调整音量
    volume.SetChannelVolumeLevel(0, mean + desiredDelta/2., None) # 左
    volume.SetChannelVolumeLevel(1, mean - desiredDelta/2., None) # 右
    # 获取并打印新音量
    volumeL = volume.GetChannelVolumeLevel(0)
    volumeR = volume.GetChannelVolumeLevel(1)
    print(f"After adjustment: L={volumeL:.2f} dB, R={volumeR:.2f} dB")
else:
    print("无需调整")

Check out similar posts by category: Audio, Python, Windows