python 设置音频默认播放设备AudioDeviceCmdlets

需求

平时需要频繁更换默认播放设备,虽然可以手动打开控制面板–声音–修改默认播放设备.但是作为程序员需要一切皆自动!
通过查找资料 发现AudioDeviceCmdlets可以实现,特此记录!

第一步:下载AudioDeviceCmdlets.dll

AudioDeviceCmdlets

第二步:安装Powershell

如果w10 可以跳过本步骤,直接下面就可以,如果是w7或者安装的Powershell版本标记老旧,需要更新Powershell
或者 运行Powershell命令报错:

无法将“Unblock-File”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查
名称的拼写,如果包括路径,请确保路径正确,然后重试。

也需要更新Powershell

第三步:准备python执行Powdshell脚本

python中运行powershell

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日

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 要实现音频重复播放并导出,可以使用Python音频处理库`pydub`。以下是一个简单的示例代码,可以将音频文件循环播放三次,并将结果导出为新的音频文件: ```python from pydub import AudioSegment # 读取音频文件 audio = AudioSegment.from_file("input_audio.wav", format="wav") # 循环播放三次 looped_audio = audio * 3 # 导出为新的音频文件 looped_audio.export("output_audio.wav", format="wav") ``` 在上面的代码中,首先使用`AudioSegment.from_file()`方法读取原始音频文件。然后,将音频文件重复三次,使用乘法运算符`*`实现。最后,使用`export()`方法将结果导出为新的音频文件。 需要注意的是,`pydub`库支持多种音频格式,如MP3、WAV、FLAC等。在调用`from_file()`和`export()`方法时,需要指定正确的音频格式。 ### 回答2: Python实现音频重复播放并导出可以通过使用音频处理库来实现。有许多库可以用于音频处理,其中一个常用的库是`pydub`。 首先,需要通过`pydub`库加载音频文件,可以使用`AudioSegment`类来完成这个任务。加载音频文件后,可以使用该类中的方法定义循环播放。下面是一个示例代码: ```python from pydub import AudioSegment def repeat_audio(audio_path, num_times): audio = AudioSegment.from_file(audio_path) repeated_audio = audio * num_times return repeated_audio audio_path = "path/to/audio/file.wav" num_times = 3 repeated_audio = repeat_audio(audio_path, num_times) output_path = "path/to/output/file.wav" repeated_audio.export(output_path, format="wav") ``` 在上面的代码中,`repeat_audio`函数接受音频文件路径和重复次数作为参数,使用`AudioSegment.from_file`方法加载音频文件,然后使用乘法操作符将音频重复指定次数。最后,使用`export`方法导出重复后的音频文件到指定路径。 需要注意的是,上述代码默认导出为.wav格式,如果需要导出为其他格式,可以更改`format`参数的值。 以上就是使用Python实现音频重复播放并导出的简单示例。根据具体需求,还可以进行更多的音频处理,如调整音量、剪辑音频等。 ### 回答3: 使用Python实现音频重复播放并导出是一种相对简单的任务。我们可以使用Python中的两个库来完成这个任务:pydub和wave。 首先,我们需要安装所需的库。可以使用以下命令在命令行中安装pydub和wave库: ``` pip install pydub pip install wave ``` 接下来,我们需要导入所需的库和模块,并读取要重复播放音频文件。假设我们的音频文件名为“audio.wav”,代码如下: ```python from pydub import AudioSegment import wave # 读取音频文件 audio = AudioSegment.from_file("audio.wav", format="wav") ``` 然后,我们可以使用pydub库中的`*`运算符来实现音频的重复播放。代码如下: ```python # 重复播放音频 repeated_audio = audio * 3 # 播放3次 ``` 重复播放后,即可使用wave库将其导出为新的音频文件。代码如下: ```python # 导出重复播放后的音频 repeated_audio.export("repeated_audio.wav", format="wav") ``` 最后,我们得到了重复播放后的音频文件“repeated_audio.wav”。 完整的代码如下: ```python from pydub import AudioSegment import wave # 读取音频文件 audio = AudioSegment.from_file("audio.wav", format="wav") # 重复播放音频 repeated_audio = audio * 3 # 播放3次 # 导出重复播放后的音频 repeated_audio.export("repeated_audio.wav", format="wav") ``` 以上就是使用Python实现音频重复播放并导出的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值