Skip to content

Instantly share code, notes, and snippets.

@grugnog
Created January 17, 2024 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grugnog/9d69c58fc884ade975fe0dea8e0c8cb5 to your computer and use it in GitHub Desktop.
Save grugnog/9d69c58fc884ade975fe0dea8e0c8cb5 to your computer and use it in GitHub Desktop.
Script to cycle through MacOS audio input/outputs with SwitchAudioSource, with configurable excluded devices
#!/usr/bin/env python3
import subprocess
import json
import sys
# Function to execute a command and return its output
def execute_command(command):
result = subprocess.run(command, stdout=subprocess.PIPE, shell=True)
return result.stdout.decode('utf-8')
# Function to switch to the next audio source
def switch_audio_source(device_type):
# List of devices to exclude categorized by type
excluded_devices = {
"input": ['USB Audio CODEC'],
"output": [],
"both": ['ZoomAudioDevice', 'DELL U2711']
}
# Get all audio sources
all_sources_output = execute_command(f'SwitchAudioSource -a -f json -t {device_type}')
all_sources = [json.loads(line) for line in all_sources_output.strip().split('\n')]
# Filter to exclude certain devices
relevant_sources = [
src for src in all_sources
if src['name'].strip() not in excluded_devices.get(device_type, []) and
src['name'].strip() not in excluded_devices.get("both", [])
]
if not relevant_sources:
print("No relevant audio sources found.")
return
# Get current audio source
current_source_output = execute_command(f'SwitchAudioSource -c -f json -t {device_type}')
current_source = json.loads(current_source_output)
# Find the next source in the list
current_index = next((i for i, src in enumerate(relevant_sources) if src['id'] == current_source['id']), -1)
next_index = (current_index + 1) % len(relevant_sources)
next_source = relevant_sources[next_index]
# Switch to the next source
execute_command(f'SwitchAudioSource -i {next_source["id"]} -t {device_type}')
print(f"Switched to {next_source['name']}")
# Main function
if __name__ == "__main__":
if len(sys.argv) != 2 or sys.argv[1] not in ['input', 'output']:
print("Usage: switch-audio [input/output]")
else:
switch_audio_source(sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment