目录
需求
平时需要频繁更换默认播放设备,虽然可以手动打开控制面板–声音–修改默认播放设备.但是作为程序员需要一切皆自动!
通过查找资料 发现AudioDeviceCmdlets可以实现,特此记录!
第一步:下载AudioDeviceCmdlets.dll
第二步:安装Powershell
如果w10 可以跳过本步骤,直接下面就可以,如果是w7或者安装的Powershell版本标记老旧,需要更新Powershell
或者 运行Powershell命令报错:
无法将“Unblock-File”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查
名称的拼写,如果包括路径,请确保路径正确,然后重试。
也需要更新Powershell
第三步:准备python执行Powdshell脚本
import os
from glob import glob
import subprocess as sp
class PowerShell:
# from scapy
def __init__(self, coding, ):
cmd = [self._where('PowerShell.exe'),
"-NoLogo", "-NonInteractive", # Do not print headers
"-Command", "-"] # Listen commands from stdin
startupinfo = sp.STARTUPINFO()
startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW
self.popen = sp.Popen(cmd, stdout=sp.PIPE, stdin=sp.PIPE, stderr=sp.STDOUT, startupinfo=startupinfo)
self.coding = coding
def __enter__(self):
return self
def __exit__(self, a, b, c):
self.popen.kill()
def run(self, cmd, timeout=15):
b_cmd = cmd.encode(encoding=self.coding)
try:
b_outs, errs = self.popen.communicate(b_cmd, timeout=timeout)
except sp.TimeoutExpired:
self.popen.kill()
b_outs, errs = self.popen.communicate()
outs = b_outs.decode(encoding=self.coding)
return outs, errs
@staticmethod
def _where(filename, dirs=None, env="PATH"):
"""Find file in current dir, in deep_lookup cache or in system path"""
if dirs is None:
dirs = []
if not isinstance(dirs, list):
dirs = [dirs]
if glob(filename):
return filename
paths = [os.curdir] + os.environ[env].split(os.path.pathsep) + dirs
try:
return next(os.path.normpath(match)
for path in paths
for match in glob(os.path.join(path, filename))
if match)
except (StopIteration, RuntimeError):
raise IOError("File not found: %s" % filename)
# 执行Powershell命令
def excute_powershell_command(shell_command):
"""
函数功能:执行Powershell命令
:param shell_command:需要执行的powershell 命令
:return:返回元组(命令结果,错误信息)
"""
try:
with PowerShell("gbk") as ps:
return ps.run(shell_command)
except UnicodeDecodeError as e:
if "'gbk' codec can't decode byte 0xac in position" in str(e):
with PowerShell("utf-8") as ps:
return ps.run(shell_command)
else:
return (0, 0)
if __name__ == '__main__':
print(excute_powershell_command("Set-AudioDevice -Index 2")[0])
第四步:注册热键,执行设置
from system_hotkey import SystemHotkey
def set_audioDevice(index: int):
load_dll = r"""New-Item "$($profile | split-path)\Modules\AudioDeviceCmdlets" -Type directory -Force
Copy-Item "C:\Users\Administrator\Desktop\AudioDeviceCmdlets.dll" "$($profile | split-path)\Modules\AudioDeviceCmdlets\AudioDeviceCmdlets.dll"
Set-Location "$($profile | Split-Path)\Modules\AudioDeviceCmdlets"
Get-ChildItem | Unblock-File
Import-Module AudioDeviceCmdlets"""
set_device_by_index = f"Set-AudioDevice -Index {index}"
if excute_powershell_command(load_dll)[1]:
print('加载dll失败')
else:
excute_powershell_command(set_device_by_index)
def consumer(event, hotkey, args):
# print(event)
# print(hotkey)
# print(args)
if args == [(0,)]:
set_audioDevice(1)
elif args == [(1,)]:
set_audioDevice(2)
def hook_key():
hk = SystemHotkey(use_xlib=False, consumer=consumer, verbose=0,
check_queue_interval=0.001)
hk.register(('control', 'alt', 'kp_0'), 0)
hk.register(('control', 'alt', 'kp_1'), 1)
if __name__ == '__main__':
hook_key()
input('------------')
附录(AudioDevice命令):
# 获取与给定的<string>对应的ID的设备
Get-AudioDevice -ID <string> # Get the device with the ID corresponding to the given <string>
# 获取具有与给定<int对应的索引的设备
Get-AudioDevice -Index <int> # Get the device with the Index corresponding to the given <int>
# 作为<AudioDevice>获取所有已启用设备的列表
Get-AudioDevice -List # Get a list of all enabled devices as <AudioDevice>
# 将默认通信播放设备设置为<AudioDevice>
Get-AudioDevice -PlaybackCommunication # Get the default communication playback device as <AudioDevice>
# 获取默认通信播放设备的静音状态为<bool>
Get-AudioDevice -PlaybackCommunicationMute # Get the default communication playback device's mute state as <bool>
# 将默认通信播放设备的音量级别设置为100<float>
Get-AudioDevice -PlaybackCommunicationVolume # Get the default communication playback device's volume level on 100 as <float>
# 获取默认播放设备为<AudioDevice>
Get-AudioDevice -Playback # Get the default playback device as <AudioDevice>
# 获取默认播放设备的静音状态为<bool>
Get-AudioDevice -PlaybackMute # Get the default playback device's mute state as <bool>
# 将默认播放设备的音量级别设置为100<float>
Get-AudioDevice -PlaybackVolume # Get the default playback device's volume level on 100 as <float>
# 获取默认的通信录制设备为<AudioDevice>
Get-AudioDevice -RecordingCommunication # Get the default communication recording device as <AudioDevice>
# 获取默认通信录制设备的静音状态为<bool>
Get-AudioDevice -RecordingCommunicationMute # Get the default communication recording device's mute state as <bool>
# 将默认通信记录设备的音量级别设置为100<float>
Get-AudioDevice -RecordingCommunicationVolume # Get the default communication recording device's volume level on 100 as <float>
# 获取默认录制设备为<AudioDevice>
Get-AudioDevice -Recording # Get the default recording device as <AudioDevice>
# 获取默认录制设备的静音状态为<bool>
Get-AudioDevice -RecordingMute # Get the default recording device's mute state as <bool>
# 将默认录制设备的音量级别设置为100<float>
Get-AudioDevice -RecordingVolume # Get the default recording device's volume level on 100 as <float>
# 将给定的播放/录制设备设置为其类型的默认设备和默认通信设备
Set-AudioDevice <AudioDevice> # Set the given playback/recording device as both the default device and the default communication device, for its type
# 将给定的播放/录制设备设置为其类型的默认通信设备,而不是默认设备
Set-AudioDevice <AudioDevice> -CommunicationOnly # Set the given playback/recording device as the default communication device and not the default device, for its type
# 将给定的播放/录制设备设置为其类型的默认设备,而不是默认通信设备
Set-AudioDevice <AudioDevice> -DefaultOnly # Set the given playback/recording device as the default device and not the default communication device, for its type
# 将ID与给定的<string>对应的设备设置为默认设备和默认通信设备(针对其类型)
Set-AudioDevice -ID <string> # Set the device with the ID corresponding to the given <string> as both the default device and the default communication device, for its type
# 将ID与给定的<string>对应的设备设置为默认通信设备,而不是其类型的默认设备
Set-AudioDevice -ID <string> -CommunicationOnly # Set the device with the ID corresponding to the given <string> as the default communication device and not the default device, for its type
# 将ID与给定的<string>对应的设备设置为默认设备,而不是其类型的默认通信设备
Set-AudioDevice -ID <string> -DefaultOnly # Set the device with the ID corresponding to the given <string> as the default device and not the default communication device, for its type
# 将具有与给定的<int>对应的索引的设备设置为默认设备和默认通信设备(针对其类型)
Set-AudioDevice -Index <int> # Set the device with the Index corresponding to the given <int> as both the default device and the default communication device, for its type
# 将具有与给定<int>对应的索引的设备设置为默认通信设备,而不是其类型的默认设备
Set-AudioDevice -Index <int> -CommunicationOnly # Set the device with the Index corresponding to the given <int> as the default communication device and not the default device, for its type
# 将具有与给定<int>对应的索引的设备设置为默认设备,而不是其类型的默认通信设备
Set-AudioDevice -Index <int> -DefaultOnly # Set the device with the Index corresponding to the given <int> as the default device and not the default communication device, for its type
# 将默认通信播放设备的静音状态设置为与当前静音状态相反的状态
Set-AudioDevice -PlaybackCommunicationMuteToggle # Set the default communication playback device's mute state to the opposite of its current mute state
# 将默认通信播放设备的静音状态设置为给定的<bool>
Set-AudioDevice -PlaybackCommunicationMute <bool> # Set the default communication playback device's mute state to the given <bool>
# 将默认通信播放设备的音量设置为100,设置为给定的<float>
Set-AudioDevice -PlaybackCommunicationVolume <float> # Set the default communication playback device's volume level on 100 to the given <float>
# 将默认播放设备的静音状态设置为与当前静音状态相反的状态
Set-AudioDevice -PlaybackMuteToggle # Set the default playback device's mute state to the opposite of its current mute state
# 将默认播放设备的静音状态设置为给定的<bool>
Set-AudioDevice -PlaybackMute <bool> # Set the default playback device's mute state to the given <bool>
# 将默认播放设备的音量设置为100,设置为给定的<float>
Set-AudioDevice -PlaybackVolume <float> # Set the default playback device's volume level on 100 to the given <float>
# 将默认通信记录设备的静音状态设置为与当前静音状态相反的状态
Set-AudioDevice -RecordingCommunicationMuteToggle # Set the default communication recording device's mute state to the opposite of its current mute state
# 将默认通信录制设备的静音状态设置为给定的<bool>
Set-AudioDevice -RecordingCommunicationMute <bool> # Set the default communication recording device's mute state to the given <bool>
# 将默认通信记录设备的音量设置为100,设置为给定的<float>
Set-AudioDevice -RecordingCommunicationVolume <float> # Set the default communication recording device's volume level on 100 to the given <float>
# 将默认录制设备的静音状态设置为与当前静音状态相反的状态
Set-AudioDevice -RecordingMuteToggle # Set the default recording device's mute state to the opposite of its current mute state
# 将默认录制设备的静音状态设置为给定的<bool>
Set-AudioDevice -RecordingMute <bool> # Set the default recording device's mute state to the given <bool>
# 将默认录制设备的音量设置为100,设置为给定的<float>
Set-AudioDevice -RecordingVolume <float> # Set the default recording device's volume level on 100 to the given <float>
# 将默认播放设备的功率输出写入100作为仪表
Write-AudioDevice -PlaybackCommunicationMeter # Write the default playback device's power output on 100 as a meter
# 将默认播放设备的功率输出写入100,作为<int>流
Write-AudioDevice -PlaybackCommunicationStream # Write the default playback device's power output on 100 as a stream of <int>
# 将默认播放设备的功率输出写入100作为仪表
Write-AudioDevice -PlaybackMeter # Write the default playback device's power output on 100 as a meter
# 将默认播放设备的功率输出写入100,作为<int>流
Write-AudioDevice -PlaybackStream # Write the default playback device's power output on 100 as a stream of <int>
# 将默认记录设备的功率输出写入100作为仪表
Write-AudioDevice -RecordingCommunicationMeter # Write the default recording device's power output on 100 as a meter
# 将默认记录设备的功率输出写入100,作为<int>流
Write-AudioDevice -RecordingCommunicationStream # Write the default recording device's power output on 100 as a stream of <int>
# 将默认记录设备的功率输出写入100作为仪表
Write-AudioDevice -RecordingMeter # Write the default recording device's power output on 100 as a meter
# 将默认记录设备的功率输出写入100,作为<int>流
Write-AudioDevice -RecordingStream # Write the default recording device's power output on 100 as a stream of <int>
记录日期:
2022.12.12日