使用 NAudio 更改默认音频输出设备

问题描述

我想使用 NAudio 更改 Windows 10 认音频输出

NAudio一个获取认音频端点的 api:

var enumerator = new MMDeviceEnumerator();
var audioOutputDevice = enumerator.GetDefaultAudioEndpoint(DataFlow.Render,Role.Console);

我想设置该认音频端点。

解决方法

最后我找不到任何关于 NAudio 的解决方案。我用 PowerShell 做到了:

  1. AudioDeviceCmdlets nuget 包从 here 添加到您的项目。

  2. 那么我们应该使用 Set-AudioDevice 命令来设置默认音频设备。它使用设备 ID 或索引。在 C# 代码中,我们需要一个 PowerShell nuget 包。该包已添加为 AudioDeviceCmdlets nuget 包的依赖项,因此请不要采取任何措施并转到下一步。

  3. 使用此代码设置默认设备:

InitialSessionState iss = InitialSessionState.CreateDefault();
iss.ImportPSModule(new string[]
{
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),"AudioDeviceCmdlets.dll")
});

Runspace runspace = RunspaceFactory.CreateRunspace(iss);
runspace.Open();

Pipeline pipeline = runspace.CreatePipeline();

Command command_set = new Command("Set-AudioDevice");
CommandParameter param_set = new CommandParameter("ID",id);
command_set.Parameters.Add(param_set);
pipeline.Commands.Add(command_set);

// Execute PowerShell script
var results = pipeline.Invoke();