Toggle between Windows audio output devices from the command line!
Here's a simple PowerShell script to toggle between two Windows audio output devices using the AudioDeviceCmdlets module. This script can be run from the command line or even bound as a macro to your keyboard for quick switching.
The full GitHub project is at https://github.com/caendesilva/WindowsToggleAudioDevice
Installation
Install AudioDeviceCmdlets
Module
-
Open PowerShell as Administrator:
- Press
Win + X
and selectWindows PowerShell (Admin)
or search for PowerShell in the Start menu and right-click to run it as administrator.
- Press
-
Install the Module:
1Install-Module -Name AudioDeviceCmdlets -Repository PSGallery -Force
List All Audio Devices
-
List Audio Devices:
1Import-Module AudioDeviceCmdlets2Get-AudioDevice -List
This command will list all audio devices with their IDs and names. Take note of the Index
values as you will need them later.
Download ToggleAudioDevice.ps1
Next, download the ToggleAudioDevice.ps1
file from GitHub, preferably into your $PATH
.
You can also just copy the following file contents, just note that it may not be up to date!
1# https://github.com/caendesilva/WindowsToggleAudioDevice/blob/master/ToggleAudioDevice.ps1 2 3Import-Module AudioDeviceCmdlets 4 5# Define the indices of your devices 6$device1Index = 3 7$device2Index = 4 8 9# Get the current default audio playback device index10$currentDeviceIndex = (Get-AudioDevice -Playback | Where-Object { $_.Default -eq "True" }).Index11 12Write-Host "Current device index: $currentDeviceIndex"13 14# Function to set the default audio playback device by index15function Set-DefaultAudioDeviceByIndex {16 param (17 [int]$deviceIndex18 )19 20 Set-AudioDevice -Index $deviceIndex21 Write-Host "Switched to device index $deviceIndex."22}23 24# Toggle the default audio playback device25if ($currentDeviceIndex -eq $device1Index) {26 Set-DefaultAudioDeviceByIndex -deviceIndex $device2Index27} else {28 Set-DefaultAudioDeviceByIndex -deviceIndex $device1Index29}
Configure ToggleAudioDevice.ps1
Now, open the ToggleAudioDevice.ps1
file and define the speaker indices found in the list above.
1# Define the indices of your devices2$device1Index = 3 # Headphones3$device2Index = 4 # Speakers
Usage
Now you can run the .\ToggleAudioDevice.ps1
script from PowerShell, and even bind it as a macro to your keyboard!
This PowerShell script provides a quick and easy way to toggle between your preferred audio devices. Make sure to adjust the device indices in the script to match your specific setup, and you'll be switching audio outputs in no time!
Syntax highlighting by Torchlight.dev