Audio Switching on the Mac (part 2)

In https://www.breu.org/audio-switching-on-the-mac/ I wrote about a method for switching audio sources on the Mac utilizing shortcuts and a simple bash script. I got a new monitor (with audio output) and a new USB-C <-> 1.5mm headphone jack and decided it was time to update the script.

Instead of using the original bash I decided to try some (very bad) python code to do the same thing but with more steps.

#!/usr/bin/env python3
import subprocess
import sys


class AudioSwitcher(object):
    def __init__(self):
        self.command = "/opt/homebrew/bin/SwitchAudioSource"
        self.valid_outputs = [
            "Studio Display Speakers",
            "USB-C to 3.5mm Headphone Jack Adapter",
            "MacBook Pro Speakers",
        ]
        self.current = self.get_current_output()
        self.all_outputs = self.get_all_outputs()
        self.number_of_outputs = len(self.valid_outputs)

    def get_current_output(self):
        return subprocess.getoutput(f"{self.command} -c")

    def get_all_outputs(self):
        return subprocess.getoutput(f"{self.command} -a").split("\n")

    def get_index_of_current(self):
        return self.valid_outputs.index(self.current)

    def announce_change(self, announce_string):
        cmd = (
            f'osascript -e "display notification \\"{announce_string}\\"'
            'with title \\"Audio Switcher\\""'
        )
        subprocess.getoutput(cmd)

    def set_output_by_index(self, old=0, new=0):
        # get the output name
        cur_name = self.valid_outputs[old]
        dest_name = self.valid_outputs[new]
        subprocess.getoutput(f"{self.command} -s '{dest_name}'")
        announce_string = f"Switched audio from '{cur_name}' to '{dest_name}'"
        print(announce_string)
        self.announce_change(announce_string)

    def set_next_output(self):
        current_index = self.get_index_of_current()
        new_index = current_index + 1
        if new_index == self.number_of_outputs:
            new_index = 0
        self.set_output_by_index(old=current_index, new=new_index)


def main():
    audio = AudioSwitcher()
    audio.set_next_output()


if __name__ == "__main__":
    main()