【问题标题】:Change default audio output device with NAudio使用 NAudio 更改默认音频输出设备
【发布时间】:2021-07-27 13:26:48
【问题描述】:

我想用 NAudio 更改 windows 10 的默认音频输出。

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

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

我想设置默认音频端点。

【问题讨论】:

    标签: c# .net naudio


    【解决方案1】:

    我将其添加为更改音频设备的更简单方法。我查看了您提到的源库AudioDeviceCmdlets,并找到了另一种方法。

    查看AudioDeviceCmdlets 类,您可以在429 行找到这段代码,其中DeviceCollection[i].ID 是新设备的ID:

     // Create a new audio PolicyConfigClient
     PolicyConfigClient client = new PolicyConfigClient();
     // Using PolicyConfigClient, set the given device as the default playback communication device
     client.SetDefaultEndpoint(DeviceCollection[i].ID, ERole.eCommunications);
     // Using PolicyConfigClient, set the given device as the default playback device
     client.SetDefaultEndpoint(DeviceCollection[i].ID, ERole.eMultimedia);
    

    好吧,就像导入这个库并进行相同的调用一样简单:

     public void SetDefaultMic(string id)
     {
         if (string.IsNullOrEmpty(id)) return;
         CoreAudioApi.PolicyConfigClient client = new CoreAudioApi.PolicyConfigClient();
         client.SetDefaultEndpoint(id, CoreAudioApi.ERole.eCommunications);
         client.SetDefaultEndpoint(id, CoreAudioApi.ERole.eMultimedia);
     }
    

    另外,通过这种方式,当您在一个线程上与 NAudio 结合使用时,您不会出现强制转换异常(添加了这个注释,因为它发生在我身上)。

    【讨论】:

      【解决方案2】:

      最后我找不到 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();
      

      【讨论】:

      • 非常感谢您提供本教程,马赫迪!知道如何将结果投射到 AudioDevice 吗?
      • 我找到了? results.Select(r=>r.BaseObject).Cast().ToList();
      猜你喜欢
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 1970-01-01
      • 2011-09-04
      • 2017-01-12
      • 2012-03-29
      相关资源
      最近更新 更多