For one thing, you are always starting out by setting device
to "Speakers"
and then checking that it is in the If
statement and thus setting it to "Headphones"
wherein the MsgBox
says so.
You never get to the else if
because the device
never starts out as Headphones
.
And even after you moved that line to above the hotkey in your edits, the problem is, if you change the device without the hot key the variable will no longer be correct.
Maybe replace with some command that would return the actual "in-use" device? I use VA.ahk at https://www.autohotkey.com/board/topic/21984-vista-audio-control-functions/ for this kind of thing.
You could also do a quick python code to get the info (as referenced here Get default audio/video device):
import winreg as wr
import platform
from contextlib import suppress
def is_os_64bit():
return platform.machine().endswith('64')
def get_default_output_device():
""" returns the PyAudio formatted name of the default output device """
import winreg as wr
read_access = wr.KEY_READ | wr.KEY_WOW64_64KEY if is_os_64bit() else wr.KEY_READ
audio_path = 'SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\MMDevices\\Audio\\Render'
audio_key = wr.OpenKeyEx(wr.HKEY_LOCAL_MACHINE, audio_path, 0, read_access)
num_devices = wr.QueryInfoKey(audio_key)[0]
active_last_used, active_device_name = -1, None
for i in range(num_devices):
device_key_path = f'{audio_path}\\{wr.EnumKey(audio_key, i)}'
device_key = wr.OpenKeyEx(wr.HKEY_LOCAL_MACHINE, device_key_path, 0, read_access)
if wr.QueryValueEx(device_key, 'DeviceState')[0] == 1: # if enabled
properties_path = f'{device_key_path}\\Properties'
properties = wr.OpenKeyEx(wr.HKEY_LOCAL_MACHINE, properties_path, 0, read_access)
device_name = wr.QueryValueEx(properties, '{b3f8fa53-0004-438e-9003-51a46e139bfc},6')[0]
device_type = wr.QueryValueEx(properties, '{a45c254e-df1c-4efd-8020-67d146a850e0},2')[0]
pa_name = f'{device_type} ({device_name})' # name shown in PyAudio
with suppress(FileNotFoundError):
last_used = wr.QueryValueEx(device_key, 'Level:0')[0]
if last_used > active_last_used: # the bigger the number, the more recent it was used
active_last_used = last_used
active_device_name = pa_name
return active_device_name
# print (get_default_output_device()) # uncomment to test in console
hth