Reputation: 5202
I want to change windows 10 default audio output with NAudio.
NAudio has an api to get the default audio endpoint:
var enumerator = new MMDeviceEnumerator();
var audioOutputDevice = enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);
I want to set that default audio endpoint.
Upvotes: 3
Views: 6694
Reputation: 51
I'm adding this as a simpler way of changing the audio device. I've looked at the source lib AudioDeviceCmdlets you mentioned and I've found another way of doing this.
Looking at the class AudioDeviceCmdlets you can find this piece of code at line 429 where DeviceCollection[i].ID is the ID of the new device:
// 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);
Well, it's as simple as importing this library an making the same call:
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);
}
Also, by doing it this way you will not get a cast exception when combined with NAudio on a thread separated (Added this note as it happened to me).
Upvotes: 5
Reputation: 5202
Finally I couldn't find any solution with NAudio. I do it with PowerShell:
Add AudioDeviceCmdlets nuget package to your project from here.
Then we should use Set-AudioDevice
command to set default audio device. It uses either device id or index. In the C# code we need a PowerShell nuget package. The package has been added as a dependency of AudioDeviceCmdlets nuget package, so take no action and go to the next step.
Use this code to set default device:
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();
Upvotes: 2