audioswitch 0.2.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ """Hold a key to switch audio output."""
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .app import main
4
+
5
+ sys.exit(main())
audioswitch/app.py ADDED
@@ -0,0 +1,285 @@
1
+ """audioswitch - hold a key to flip the default audio output between two devices.
2
+
3
+ Runs in the system tray. Everything that touches the operating system lives in a
4
+ backend module (linux.py / windows.py); this file is the shared UI and logic.
5
+ """
6
+ import json
7
+ import signal
8
+ import sys
9
+
10
+ from PyQt6.QtCore import Qt, QTimer
11
+ from PyQt6.QtGui import QAction, QIcon
12
+ from PyQt6.QtNetwork import QLocalServer, QLocalSocket
13
+ from PyQt6.QtWidgets import (
14
+ QApplication, QCheckBox, QComboBox, QDoubleSpinBox, QFormLayout, QHBoxLayout,
15
+ QLabel, QMenu, QPushButton, QSlider, QSystemTrayIcon, QVBoxLayout, QWidget,
16
+ )
17
+
18
+ if sys.platform == "win32":
19
+ from . import windows as backend
20
+ else:
21
+ from . import linux as backend
22
+
23
+ APP = "audioswitch"
24
+ CONFIG = backend.CONFIG_DIR / "config.json"
25
+ DEFAULTS = {"key": backend.MUTE_KEY, "hold": 0.8, "sink_a": "", "sink_b": "", "sidetone": None}
26
+
27
+
28
+ def load_config():
29
+ cfg = dict(DEFAULTS)
30
+ try:
31
+ cfg.update(json.loads(CONFIG.read_text()))
32
+ except (OSError, ValueError):
33
+ pass
34
+ return cfg
35
+
36
+
37
+ def save_config(cfg):
38
+ CONFIG.parent.mkdir(parents=True, exist_ok=True)
39
+ CONFIG.write_text(json.dumps(cfg, indent=2))
40
+
41
+
42
+ class Window(QWidget):
43
+ def __init__(self):
44
+ super().__init__()
45
+ first_run = not CONFIG.exists()
46
+ self.cfg = load_config()
47
+ if first_run: # a hotkey app is no use unless it is running, so default to on
48
+ save_config(self.cfg)
49
+ backend.set_autostart(True)
50
+ elif backend.autostart_enabled():
51
+ backend.set_autostart(True) # refresh the entry in case the install path changed
52
+ self.capturing = False
53
+ self.fired = False
54
+ self.sidetone_device = None
55
+ icon = QIcon(str(backend.ICON))
56
+ self.setWindowTitle("Audio Switch")
57
+ self.setWindowIcon(icon)
58
+
59
+ self.key_button = QPushButton()
60
+ self.key_button.clicked.connect(self.start_capture)
61
+ self.hold = QDoubleSpinBox(minimum=0.2, maximum=5.0, singleStep=0.1, suffix=" s")
62
+ self.hold.setValue(self.cfg["hold"])
63
+ self.hold.valueChanged.connect(self.changed)
64
+ key_row = QHBoxLayout()
65
+ key_row.addWidget(self.key_button, 1)
66
+ key_row.addWidget(QLabel("hold for"))
67
+ key_row.addWidget(self.hold)
68
+
69
+ self.sink_a, self.sink_b = QComboBox(), QComboBox()
70
+ for combo in (self.sink_a, self.sink_b):
71
+ combo.activated.connect(self.changed)
72
+
73
+ self.sidetone = QSlider(Qt.Orientation.Horizontal, minimum=0, maximum=100)
74
+ self.sidetone_on = QCheckBox("On")
75
+ self.sidetone_label = QLabel()
76
+ self.sidetone.valueChanged.connect(self.sidetone_changed)
77
+ self.sidetone_on.toggled.connect(self.sidetone_changed)
78
+ side_row = QHBoxLayout()
79
+ side_row.addWidget(self.sidetone_on)
80
+ side_row.addWidget(self.sidetone, 1)
81
+ side_row.addWidget(self.sidetone_label)
82
+
83
+ self.autostart = QCheckBox("Start at login")
84
+ self.autostart.setChecked(backend.autostart_enabled())
85
+ self.autostart.toggled.connect(backend.set_autostart)
86
+ switch_now = QPushButton("Switch now")
87
+ switch_now.clicked.connect(self.switch)
88
+ self.status = QLabel()
89
+ bottom = QHBoxLayout()
90
+ bottom.addWidget(self.autostart)
91
+ bottom.addStretch(1)
92
+ bottom.addWidget(switch_now)
93
+
94
+ form = QFormLayout()
95
+ form.addRow("Hotkey", key_row)
96
+ form.addRow("Output A", self.sink_a)
97
+ form.addRow("Output B", self.sink_b)
98
+ form.addRow("Sidetone", side_row)
99
+ layout = QVBoxLayout(self)
100
+ layout.addLayout(form)
101
+ layout.addWidget(self.status)
102
+ layout.addLayout(bottom)
103
+ self.setMinimumWidth(460)
104
+
105
+ self.hold_timer = QTimer(singleShot=True)
106
+ self.hold_timer.timeout.connect(self.long_press)
107
+ self.watcher = backend.KeyWatcher(self.on_key)
108
+ self.refresh_timer = QTimer()
109
+ self.refresh_timer.timeout.connect(self.refresh)
110
+ self.refresh_timer.start(3000)
111
+ self.show_key()
112
+ self.refresh()
113
+
114
+ self.tray = QSystemTrayIcon(icon, self)
115
+ menu = QMenu()
116
+ for text, slot in (("Switch output", self.switch), ("Settings…", self.reveal),
117
+ ("Quit", QApplication.quit)):
118
+ action = QAction(text, self)
119
+ action.triggered.connect(slot)
120
+ menu.addAction(action)
121
+ self.tray.setContextMenu(menu)
122
+ self.tray.setToolTip("Audio Switch")
123
+ self.tray.activated.connect(
124
+ lambda reason: reason == QSystemTrayIcon.ActivationReason.Trigger and self.reveal())
125
+ self.tray.show()
126
+
127
+ # -- state ---------------------------------------------------------------
128
+
129
+ def refresh(self):
130
+ """Pick up newly connected outputs and the sidetone device."""
131
+ sinks = backend.list_sinks()
132
+ known = [name for name, _ in sinks]
133
+ for combo, key in ((self.sink_a, "sink_a"), (self.sink_b, "sink_b")):
134
+ if combo.view().isVisible():
135
+ continue
136
+ wanted = list(sinks)
137
+ if self.cfg[key] and self.cfg[key] not in known:
138
+ wanted.append((self.cfg[key], "(disconnected) " + self.cfg[key]))
139
+ if [combo.itemData(i) for i in range(combo.count())] != [name for name, _ in wanted]:
140
+ combo.clear()
141
+ for name, desc in wanted:
142
+ combo.addItem(desc, name)
143
+ combo.setCurrentIndex(combo.findData(self.cfg[key]))
144
+
145
+ device = backend.sidetone_device()
146
+ if device != self.sidetone_device:
147
+ self.sidetone_device = device
148
+ if device is not None and self.cfg["sidetone"] is not None:
149
+ backend.set_sidetone(device, *self.cfg["sidetone"])
150
+ self.sidetone.setEnabled(device is not None)
151
+ self.sidetone_on.setEnabled(device is not None)
152
+ if device is None:
153
+ self.sidetone_label.setText(backend.NO_SIDETONE)
154
+ elif not self.sidetone.isSliderDown():
155
+ percent, on = backend.get_sidetone(device)
156
+ self.sidetone.blockSignals(True)
157
+ self.sidetone_on.blockSignals(True)
158
+ self.sidetone.setValue(percent)
159
+ self.sidetone_on.setChecked(on)
160
+ self.sidetone.blockSignals(False)
161
+ self.sidetone_on.blockSignals(False)
162
+ self.sidetone_label.setText(f"{percent}%")
163
+
164
+ def changed(self, *_):
165
+ self.cfg["hold"] = round(self.hold.value(), 2)
166
+ self.cfg["sink_a"] = self.sink_a.currentData() or ""
167
+ self.cfg["sink_b"] = self.sink_b.currentData() or ""
168
+ save_config(self.cfg)
169
+
170
+ def sidetone_changed(self, *_):
171
+ if self.sidetone_device is None:
172
+ return
173
+ percent, on = self.sidetone.value(), self.sidetone_on.isChecked()
174
+ backend.set_sidetone(self.sidetone_device, percent, on)
175
+ self.sidetone_label.setText(f"{percent}%")
176
+ self.cfg["sidetone"] = [percent, on]
177
+ save_config(self.cfg)
178
+
179
+ # -- hotkey --------------------------------------------------------------
180
+
181
+ def show_key(self):
182
+ self.key_button.setText(backend.key_name(self.cfg["key"]))
183
+
184
+ def start_capture(self):
185
+ self.capturing = True
186
+ self.key_button.setText("Press a key…")
187
+
188
+ def on_key(self, code, pressed):
189
+ if self.capturing:
190
+ if pressed:
191
+ self.capturing = False
192
+ self.cfg["key"] = code
193
+ save_config(self.cfg)
194
+ self.show_key()
195
+ backend.claim_mute_key(code == backend.MUTE_KEY)
196
+ return
197
+ if code != self.cfg["key"]:
198
+ return
199
+ if pressed:
200
+ self.fired = False
201
+ self.hold_timer.start(int(self.cfg["hold"] * 1000))
202
+ else:
203
+ self.hold_timer.stop()
204
+ if not self.fired and code == backend.MUTE_KEY:
205
+ backend.toggle_mute() # short tap: this app does the muting, see claim_mute_key
206
+
207
+ def long_press(self):
208
+ self.fired = True
209
+ self.switch()
210
+
211
+ def switch(self):
212
+ sinks = dict(backend.list_sinks())
213
+ a, b = self.cfg["sink_a"], self.cfg["sink_b"]
214
+ target = b if backend.default_sink() == a else a
215
+ if not a or not b or a == b:
216
+ message = "Choose two different outputs first"
217
+ elif target not in sinks:
218
+ message = "Output not connected"
219
+ else:
220
+ backend.switch_to(target)
221
+ QTimer.singleShot(500, lambda: backend.settle(target))
222
+ message = sinks[target]
223
+ self.status.setText(message)
224
+ backend.notify(message, self.tray)
225
+
226
+ # -- window --------------------------------------------------------------
227
+
228
+ def reveal(self):
229
+ self.refresh()
230
+ self.show()
231
+ self.raise_()
232
+ self.activateWindow()
233
+
234
+ def closeEvent(self, event):
235
+ self.capturing = False
236
+ self.show_key()
237
+ event.ignore()
238
+ self.hide()
239
+
240
+
241
+ def main():
242
+ args = sys.argv[1:]
243
+ if "--install-launcher" in args:
244
+ print(f"wrote {backend.install_launcher()}")
245
+ return 0
246
+
247
+ socket = QLocalSocket()
248
+ socket.connectToServer(APP)
249
+ if socket.waitForConnected(300): # already running: hand the request over
250
+ socket.write(b"toggle" if "--toggle" in args else b"show")
251
+ socket.waitForBytesWritten(500)
252
+ return 0
253
+
254
+ app = QApplication(sys.argv)
255
+ app.setApplicationName(APP)
256
+ app.setDesktopFileName(APP)
257
+ app.setQuitOnLastWindowClosed(False)
258
+ window = Window()
259
+ backend.claim_mute_key(window.cfg["key"] == backend.MUTE_KEY)
260
+ app.aboutToQuit.connect(lambda: backend.claim_mute_key(False))
261
+ for name in ("SIGTERM", "SIGINT", "SIGHUP"):
262
+ if hasattr(signal, name):
263
+ signal.signal(getattr(signal, name), lambda *_: app.quit())
264
+
265
+ QLocalServer.removeServer(APP)
266
+ server = QLocalServer()
267
+
268
+ def incoming():
269
+ conn = server.nextPendingConnection()
270
+ conn.waitForReadyRead(500)
271
+ window.switch() if bytes(conn.readAll()) == b"toggle" else window.reveal()
272
+ conn.close()
273
+
274
+ server.newConnection.connect(incoming)
275
+ server.listen(APP)
276
+
277
+ if "--toggle" in args:
278
+ window.switch()
279
+ elif "--hidden" not in args:
280
+ window.show()
281
+ return app.exec()
282
+
283
+
284
+ if __name__ == "__main__":
285
+ sys.exit(main())
audioswitch/icon.svg ADDED
@@ -0,0 +1,6 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
2
+ <path d="M12 38v-8a20 20 0 0 1 40 0v8" fill="none" stroke="#3daee9" stroke-width="5" stroke-linecap="round"/>
3
+ <rect x="7" y="34" width="11" height="18" rx="4" fill="#3daee9"/>
4
+ <rect x="46" y="34" width="11" height="18" rx="4" fill="#3daee9"/>
5
+ <path d="M25 40h14m-4-5 5 5-5 5M39 52H25m4-5-5 5 5 5" fill="none" stroke="#f67400" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/>
6
+ </svg>
audioswitch/linux.py ADDED
@@ -0,0 +1,231 @@
1
+ """Linux backend: evdev for keys, PipeWire for audio, ALSA for sidetone."""
2
+ import json
3
+ import os
4
+ import re
5
+ import shutil
6
+ import subprocess
7
+ import sys
8
+ from pathlib import Path
9
+
10
+ import evdev
11
+ from evdev import ecodes
12
+ from PyQt6.QtCore import QSocketNotifier, QTimer
13
+
14
+ APP = "audioswitch"
15
+ ICON = Path(__file__).with_name("icon.svg")
16
+ CONFIG_DIR = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / APP
17
+ AUTOSTART = Path.home() / ".config/autostart" / f"{APP}.desktop"
18
+ LAUNCHER = Path.home() / ".local/share/applications" / f"{APP}.desktop"
19
+ MUTE_KEY = ecodes.KEY_MUTE
20
+ NO_SIDETONE = "no device"
21
+
22
+
23
+ def run(*cmd):
24
+ try:
25
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=5).stdout
26
+ except (OSError, subprocess.SubprocessError):
27
+ return ""
28
+
29
+
30
+ def key_name(code):
31
+ name = ecodes.KEY.get(code) or ecodes.BTN.get(code) or f"KEY_{code}"
32
+ if isinstance(name, (list, tuple)):
33
+ name = next((n for n in name if "MIN_INTERESTING" not in n), name[0])
34
+ return name.removeprefix("KEY_").replace("_", " ").title()
35
+
36
+
37
+ # --- audio -----------------------------------------------------------------
38
+
39
+ def list_sinks():
40
+ """[(id, description)] of the connected outputs."""
41
+ try:
42
+ return [(s["name"], s["description"]) for s in json.loads(run("pactl", "-f", "json", "list", "sinks"))]
43
+ except ValueError:
44
+ return []
45
+
46
+
47
+ def default_sink():
48
+ return run("pactl", "get-default-sink").strip()
49
+
50
+
51
+ def playing_streams():
52
+ """(node id, sink index) for every playback stream."""
53
+ try:
54
+ streams = json.loads(run("pactl", "-f", "json", "list", "sink-inputs"))
55
+ return [(int(s["properties"]["object.id"]), s["sink"]) for s in streams
56
+ if "object.id" in s.get("properties", {})]
57
+ except (ValueError, TypeError):
58
+ return []
59
+
60
+
61
+ def switch_to(target):
62
+ run("pactl", "set-default-sink", target)
63
+ for node, _ in playing_streams():
64
+ run("pw-metadata", "-n", "default", str(node), "target.object", target)
65
+
66
+
67
+ def settle(target):
68
+ """Relink streams the session manager refused to move; call shortly after switch_to.
69
+
70
+ Apps that pick an output device themselves (e.g. a Teams call in Firefox) are
71
+ pinned to it, so their ports have to be rewired by hand.
72
+ """
73
+ try:
74
+ sink_index = next(s["index"] for s in json.loads(run("pactl", "-f", "json", "list", "sinks"))
75
+ if s["name"] == target)
76
+ stuck = [node for node, sink in playing_streams() if sink != sink_index]
77
+ if not stuck:
78
+ return
79
+ objs = json.loads(run("pw-dump"))
80
+ except (ValueError, StopIteration):
81
+ return
82
+
83
+ def ports(node, direction):
84
+ return {o["info"]["props"].get("audio.channel"): o["id"] for o in objs
85
+ if o["type"].endswith("Port") and o["info"]["direction"] == direction
86
+ and o["info"]["props"].get("node.id") == node}
87
+
88
+ sink_node = next((o["id"] for o in objs if o["type"].endswith("Node")
89
+ and o["info"]["props"].get("node.name") == target), None)
90
+ inputs = ports(sink_node, "input")
91
+ if not inputs:
92
+ return
93
+ for node in stuck:
94
+ for o in objs:
95
+ if o["type"].endswith("Link") and o["info"]["output-node-id"] == node:
96
+ run("pw-link", "-d", str(o["id"]))
97
+ for channel, port in ports(node, "output").items():
98
+ for dest in ([inputs[channel]] if channel in inputs else inputs.values()):
99
+ run("pw-link", str(port), str(dest))
100
+
101
+
102
+ def toggle_mute():
103
+ """Toggle mute on the default output and show the desktop's on-screen indicator."""
104
+ run("pactl", "set-sink-mute", "@DEFAULT_SINK@", "toggle")
105
+ muted = "yes" in run("pactl", "get-sink-mute", "@DEFAULT_SINK@")
106
+ run("busctl", "--user", "call", "org.kde.plasmashell", "/org/kde/osdService",
107
+ "org.kde.osdService", "showText", "ss",
108
+ "audio-volume-muted" if muted else "audio-volume-high", "Muted" if muted else "Unmuted")
109
+
110
+
111
+ def claim_mute_key(claimed):
112
+ """Take the Volume Mute key away from KDE's own Mute action, or give it back.
113
+
114
+ KDE mutes the moment the key goes down (and again on every auto-repeat), which
115
+ flickers during a long hold. While this app owns the key it mutes on a short tap itself.
116
+ """
117
+ run("busctl", "--user", "call", "org.kde.kglobalaccel", "/kglobalaccel", "org.kde.KGlobalAccel",
118
+ "setForeignShortcut", "asai", "4", "kmix", "mute", "Audio Volume", "Mute",
119
+ *(["0"] if claimed else ["1", "16777329"]))
120
+
121
+
122
+ def notify(text, tray):
123
+ subprocess.Popen(["notify-send", "-a", "Audio Switch", "-i", str(ICON), "-t", "2000",
124
+ "Audio output", text],
125
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
126
+
127
+
128
+ # --- sidetone --------------------------------------------------------------
129
+
130
+ def sidetone_device():
131
+ """Index of the first ALSA card with a Sidetone control, or None."""
132
+ try:
133
+ cards = re.findall(r"^\s*(\d+)\s+\[", Path("/proc/asound/cards").read_text(), re.M)
134
+ except OSError:
135
+ return None
136
+ for card in cards:
137
+ if "'Sidetone'" in run("amixer", "-c", card, "scontrols"):
138
+ return card
139
+ return None
140
+
141
+
142
+ def get_sidetone(card):
143
+ out = run("amixer", "-c", card, "sget", "Sidetone")
144
+ pct = re.search(r"\[(\d+)%\]", out)
145
+ return (int(pct.group(1)) if pct else 0), "[off]" not in out
146
+
147
+
148
+ def set_sidetone(card, percent, on):
149
+ run("amixer", "-c", card, "sset", "Sidetone", f"{percent}%", "on" if on else "off")
150
+
151
+
152
+ # --- start at login / launcher ---------------------------------------------
153
+
154
+ def desktop_entry(*args):
155
+ """A .desktop file that starts this app, however it was installed."""
156
+ command = shutil.which(APP) or f"{sys.executable} -m {APP}"
157
+ return ("[Desktop Entry]\nType=Application\nName=Audio Switch\n"
158
+ "Comment=Hold a key to switch audio output\n"
159
+ f"Exec={' '.join([command, *args])}\nIcon={ICON}\n"
160
+ "Categories=AudioVideo;Audio;Settings;\n")
161
+
162
+
163
+ def autostart_enabled():
164
+ return AUTOSTART.exists()
165
+
166
+
167
+ def set_autostart(enabled):
168
+ if enabled:
169
+ AUTOSTART.parent.mkdir(parents=True, exist_ok=True)
170
+ AUTOSTART.write_text(desktop_entry("--hidden"))
171
+ else:
172
+ AUTOSTART.unlink(missing_ok=True)
173
+
174
+
175
+ def install_launcher():
176
+ LAUNCHER.parent.mkdir(parents=True, exist_ok=True)
177
+ LAUNCHER.write_text(desktop_entry())
178
+ return LAUNCHER
179
+
180
+
181
+ # --- hotkey ----------------------------------------------------------------
182
+
183
+ class KeyWatcher:
184
+ """Reads key events from every keyboard-like evdev device."""
185
+
186
+ def __init__(self, on_key):
187
+ self.on_key = on_key # callback(code, pressed)
188
+ self.devices = {} # path -> (device, notifier)
189
+ self.rescan_timer = QTimer()
190
+ self.rescan_timer.timeout.connect(self.rescan)
191
+ self.rescan_timer.start(3000)
192
+ self.rescan()
193
+
194
+ def rescan(self):
195
+ paths = set(evdev.list_devices())
196
+ for path in list(self.devices):
197
+ if path not in paths:
198
+ self.drop(path)
199
+ for path in paths - set(self.devices):
200
+ try:
201
+ dev = evdev.InputDevice(path)
202
+ if ecodes.EV_KEY not in dev.capabilities():
203
+ dev.close()
204
+ continue
205
+ except OSError:
206
+ continue
207
+ notifier = QSocketNotifier(dev.fd, QSocketNotifier.Type.Read)
208
+ notifier.activated.connect(lambda *_, p=path: self.read(p))
209
+ self.devices[path] = (dev, notifier)
210
+
211
+ def drop(self, path):
212
+ dev, notifier = self.devices.pop(path)
213
+ notifier.setEnabled(False)
214
+ notifier.deleteLater()
215
+ try:
216
+ dev.close()
217
+ except OSError:
218
+ pass
219
+
220
+ def read(self, path):
221
+ if path not in self.devices:
222
+ return
223
+ try:
224
+ for event in self.devices[path][0].read():
225
+ is_mouse = ecodes.BTN_MOUSE <= event.code <= ecodes.BTN_TASK
226
+ if event.type == ecodes.EV_KEY and event.value in (0, 1) and not is_mouse:
227
+ self.on_key(event.code, event.value == 1)
228
+ except BlockingIOError:
229
+ pass
230
+ except OSError:
231
+ self.drop(path)
audioswitch/windows.py ADDED
@@ -0,0 +1,204 @@
1
+ """Windows backend: low-level keyboard hook for keys, Core Audio (pycaw) for devices.
2
+
3
+ Sidetone is not implemented here yet.
4
+ """
5
+ import ctypes
6
+ import os
7
+ import shutil
8
+ import sys
9
+ import warnings
10
+ import winreg
11
+ from ctypes import wintypes
12
+ from pathlib import Path
13
+
14
+ from comtypes import COMError
15
+ from PyQt6.QtCore import QTimer
16
+ from PyQt6.QtWidgets import QSystemTrayIcon
17
+ from pycaw.constants import DEVICE_STATE, EDataFlow, ERole
18
+ from pycaw.pycaw import AudioUtilities
19
+
20
+ APP = "audioswitch"
21
+ ICON = Path(__file__).with_name("icon.svg")
22
+ CONFIG_DIR = Path(os.environ.get("APPDATA", Path.home())) / APP
23
+ RUN_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run"
24
+ MUTE_KEY = 0xAD # VK_VOLUME_MUTE
25
+ NO_SIDETONE = "not on Windows yet"
26
+
27
+ KEY_NAMES = {
28
+ 0xAD: "Mute", 0xAE: "Volume Down", 0xAF: "Volume Up", 0xB0: "Next Track",
29
+ 0xB1: "Previous Track", 0xB2: "Stop", 0xB3: "Play/Pause", 0x13: "Pause",
30
+ 0x91: "Scroll Lock", 0x2C: "Print Screen", 0x2D: "Insert", 0x14: "Caps Lock",
31
+ **{0x70 + i: f"F{i + 1}" for i in range(24)},
32
+ }
33
+
34
+ user32 = ctypes.WinDLL("user32", use_last_error=True)
35
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
36
+ LRESULT = ctypes.c_ssize_t
37
+ HOOKPROC = ctypes.WINFUNCTYPE(LRESULT, ctypes.c_int, wintypes.WPARAM, wintypes.LPARAM)
38
+ user32.SetWindowsHookExW.argtypes = [ctypes.c_int, HOOKPROC, wintypes.HMODULE, wintypes.DWORD]
39
+ user32.SetWindowsHookExW.restype = wintypes.HHOOK
40
+ user32.CallNextHookEx.argtypes = [wintypes.HHOOK, ctypes.c_int, wintypes.WPARAM, wintypes.LPARAM]
41
+ user32.CallNextHookEx.restype = LRESULT
42
+ user32.UnhookWindowsHookEx.argtypes = [wintypes.HHOOK]
43
+ kernel32.GetModuleHandleW.argtypes = [wintypes.LPCWSTR]
44
+ kernel32.GetModuleHandleW.restype = wintypes.HMODULE
45
+
46
+ _swallow_mute = False
47
+
48
+
49
+ class KBDLLHOOKSTRUCT(ctypes.Structure):
50
+ _fields_ = [("vkCode", wintypes.DWORD), ("scanCode", wintypes.DWORD),
51
+ ("flags", wintypes.DWORD), ("time", wintypes.DWORD),
52
+ ("dwExtraInfo", ctypes.c_size_t)]
53
+
54
+
55
+ def key_name(code):
56
+ if code in KEY_NAMES:
57
+ return KEY_NAMES[code]
58
+ buf = ctypes.create_unicode_buffer(64)
59
+ scan = user32.MapVirtualKeyW(code, 0)
60
+ if scan and user32.GetKeyNameTextW(scan << 16, buf, 64):
61
+ return buf.value
62
+ return f"Key 0x{code:02X}"
63
+
64
+
65
+ # --- audio -----------------------------------------------------------------
66
+
67
+ def list_sinks():
68
+ """[(id, description)] of the connected outputs."""
69
+ with warnings.catch_warnings():
70
+ warnings.simplefilter("ignore", UserWarning)
71
+ devices = AudioUtilities.GetAllDevices(data_flow=EDataFlow.eRender.value,
72
+ device_state=DEVICE_STATE.ACTIVE.value)
73
+ return [(d.id, d.FriendlyName or d.id) for d in devices]
74
+
75
+
76
+ def default_sink():
77
+ try:
78
+ device = AudioUtilities.GetSpeakers()
79
+ except (OSError, COMError): # no output device at all
80
+ return ""
81
+ return device.id if device else ""
82
+
83
+
84
+ def switch_to(target):
85
+ # Streams that follow the default device move by themselves on Windows.
86
+ AudioUtilities.SetDefaultDevice(
87
+ target, roles=[ERole.eConsole, ERole.eMultimedia, ERole.eCommunications])
88
+
89
+
90
+ def settle(target):
91
+ """Nothing to do: Windows offers no way to move streams an app pinned to a device."""
92
+
93
+
94
+ def toggle_mute():
95
+ """Replay the mute key so Windows mutes and shows its own volume flyout.
96
+
97
+ Injected events are ignored by our hook, so this does not loop.
98
+ """
99
+ user32.keybd_event(MUTE_KEY, 0, 0, 0)
100
+ user32.keybd_event(MUTE_KEY, 0, 2, 0) # KEYEVENTF_KEYUP
101
+
102
+
103
+ def claim_mute_key(claimed):
104
+ """While claimed, the hook swallows the physical mute key and the app mutes on a short tap."""
105
+ global _swallow_mute
106
+ _swallow_mute = claimed
107
+
108
+
109
+ def notify(text, tray):
110
+ tray.showMessage("Audio output", text, QSystemTrayIcon.MessageIcon.NoIcon, 2000)
111
+
112
+
113
+ # --- sidetone (not implemented) ---------------------------------------------
114
+
115
+ def sidetone_device():
116
+ return None
117
+
118
+
119
+ def get_sidetone(device):
120
+ return 0, False
121
+
122
+
123
+ def set_sidetone(device, percent, on):
124
+ pass
125
+
126
+
127
+ # --- start at login / launcher ---------------------------------------------
128
+
129
+ def _program():
130
+ """(executable, arguments) that start this app, however it was installed."""
131
+ if getattr(sys, "frozen", False): # standalone .exe
132
+ return sys.executable, ""
133
+ exe = shutil.which(APP)
134
+ return (exe, "") if exe else (sys.executable, f"-m {APP}")
135
+
136
+
137
+ def _command(*args):
138
+ exe, base_args = _program()
139
+ return " ".join(filter(None, [f'"{exe}"', base_args, *args]))
140
+
141
+
142
+ def autostart_enabled():
143
+ try:
144
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, RUN_KEY) as key:
145
+ winreg.QueryValueEx(key, APP)
146
+ return True
147
+ except OSError:
148
+ return False
149
+
150
+
151
+ def set_autostart(enabled):
152
+ with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, RUN_KEY, 0, winreg.KEY_SET_VALUE) as key:
153
+ if enabled:
154
+ winreg.SetValueEx(key, APP, 0, winreg.REG_SZ, _command("--hidden"))
155
+ else:
156
+ try:
157
+ winreg.DeleteValue(key, APP)
158
+ except OSError:
159
+ pass
160
+
161
+
162
+ def install_launcher():
163
+ """Create a Start Menu shortcut."""
164
+ import comtypes.client
165
+ menu = Path(os.environ["APPDATA"]) / "Microsoft/Windows/Start Menu/Programs"
166
+ path = menu / "Audio Switch.lnk"
167
+ shortcut = comtypes.client.CreateObject("WScript.Shell").CreateShortcut(str(path))
168
+ shortcut.TargetPath, shortcut.Arguments = _program()
169
+ shortcut.Save()
170
+ return path
171
+
172
+
173
+ # --- hotkey ----------------------------------------------------------------
174
+
175
+ class KeyWatcher:
176
+ """Global low-level keyboard hook. Must be created on the GUI thread (it needs a message loop)."""
177
+
178
+ def __init__(self, on_key):
179
+ self.on_key = on_key # callback(code, pressed)
180
+ self.held = set()
181
+ self.proc = HOOKPROC(self.hook) # keep a reference so it is not garbage collected
182
+ self.handle = user32.SetWindowsHookExW(13, self.proc, kernel32.GetModuleHandleW(None), 0)
183
+ if not self.handle:
184
+ raise ctypes.WinError(ctypes.get_last_error())
185
+
186
+ def hook(self, n_code, w_param, l_param):
187
+ if n_code == 0:
188
+ event = ctypes.cast(l_param, ctypes.POINTER(KBDLLHOOKSTRUCT)).contents
189
+ if not event.flags & 0x10: # skip injected events (see toggle_mute)
190
+ code = event.vkCode
191
+ if w_param in (0x100, 0x104): # key down; auto-repeat sends it again
192
+ if code not in self.held:
193
+ self.held.add(code)
194
+ self.emit(code, True)
195
+ elif w_param in (0x101, 0x105):
196
+ self.held.discard(code)
197
+ self.emit(code, False)
198
+ if _swallow_mute and code == MUTE_KEY:
199
+ return 1
200
+ return user32.CallNextHookEx(None, n_code, w_param, l_param)
201
+
202
+ def emit(self, code, pressed):
203
+ # Windows drops hooks that are slow to return, so do the work after returning.
204
+ QTimer.singleShot(0, lambda: self.on_key(code, pressed))
@@ -0,0 +1,145 @@
1
+ Metadata-Version: 2.5
2
+ Name: audioswitch
3
+ Version: 0.2.2
4
+ Summary: Hold a key to switch audio output between two devices, with a sidetone slider
5
+ Project-URL: Repository, https://github.com/DeastinY/audioswitch
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: audio,headphones,headset,hotkey,output-switcher,pipewire,sidetone,tray
9
+ Classifier: Operating System :: Microsoft :: Windows
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Multimedia :: Sound/Audio
13
+ Requires-Python: >=3.10
14
+ Requires-Dist: evdev>=1.6; sys_platform == 'linux'
15
+ Requires-Dist: pycaw>=20251023; sys_platform == 'win32'
16
+ Requires-Dist: pyqt6>=6.5
17
+ Description-Content-Type: text/markdown
18
+
19
+ # audioswitch
20
+
21
+ [![check](https://github.com/DeastinY/audioswitch/actions/workflows/check.yml/badge.svg)](https://github.com/DeastinY/audioswitch/actions/workflows/check.yml)
22
+ [![version](https://img.shields.io/github/v/tag/DeastinY/audioswitch?label=version&sort=semver)](https://github.com/DeastinY/audioswitch/tags)
23
+ ![python](https://img.shields.io/badge/python-3.10%2B-3776AB?logo=python&logoColor=white)
24
+ ![linux](https://img.shields.io/badge/Linux-PipeWire-FCC624?logo=linux&logoColor=black)
25
+ ![windows](https://img.shields.io/badge/Windows-10%20%2F%2011-0078D6)
26
+ ![vibecoded](https://img.shields.io/badge/vibecoded-with%20Claude-d97757)
27
+ [![license](https://img.shields.io/badge/license-MIT-green)](LICENSE)
28
+
29
+ > **Disclaimer:** this project was written with AI assistance (Claude). It is a small personal tool; review it before relying on it.
30
+
31
+ Hold a key to flip your audio output between two devices — for example, hold the
32
+ mute button for a second to jump between speakers and a headset. A short tap of
33
+ the same key still mutes.
34
+
35
+ A small tray app with a settings window:
36
+
37
+ - **Hotkey** — click and press any key; the hold time is adjustable.
38
+ - **Output A / B** — the two devices to switch between. Playing streams move along.
39
+ - **Sidetone** (Linux) — on/off and level for headsets that expose a `Sidetone` mixer control.
40
+ - **Start at login**.
41
+
42
+ | | Linux | Windows |
43
+ |---|---|---|
44
+ | Hold-to-switch hotkey, tap to mute | yes | yes |
45
+ | Moves streams an app pinned to a device (e.g. a browser call) | yes | no |
46
+ | Sidetone slider | yes | not yet |
47
+ | Status | used daily | checked in CI only, not yet on real hardware |
48
+
49
+ ## Install
50
+
51
+ **Linux or Windows, with [uv](https://docs.astral.sh/uv/):**
52
+
53
+ ```sh
54
+ uv tool install git+https://github.com/DeastinY/audioswitch
55
+ audioswitch --install-launcher # optional: add it to the application / Start menu
56
+ audioswitch
57
+ ```
58
+
59
+ Update with `uv tool upgrade audioswitch`, remove with `uv tool uninstall audioswitch`.
60
+
61
+ **Windows, without installing anything:** download `audioswitch.exe` from the
62
+ [latest release](https://github.com/DeastinY/audioswitch/releases/latest) and run it.
63
+
64
+ **Arch Linux:** a `PKGBUILD` is in [`packaging/aur`](packaging/aur).
65
+
66
+ The app starts itself at login from the first run on; untick "Start at login" in
67
+ its window if you do not want that.
68
+
69
+ ### Linux requirements
70
+
71
+ - PipeWire with `pipewire-pulse` and WirePlumber, and the tools `pactl`,
72
+ `pw-metadata`, `pw-link`, `pw-dump` (packages `pipewire`, `libpulse` on Arch).
73
+ - `amixer` (`alsa-utils`) for the sidetone slider.
74
+ - Read access to `/dev/input/event*` for the hotkey. Usually that means being in
75
+ the `input` group: `sudo usermod -aG input $USER`, then log out and back in.
76
+ Note that this lets your user's programs read all keyboard input.
77
+
78
+ ### Windows requirements
79
+
80
+ Windows 10 or 11. Nothing else; uv fetches Python and the dependencies.
81
+
82
+ ## Which headsets and speakers work?
83
+
84
+ **Switching** works with any two outputs your system lists: USB headsets, USB
85
+ DACs and speakers, onboard audio, HDMI, Bluetooth.
86
+
87
+ **The sidetone slider** works with headsets that implement mic monitoring as a
88
+ standard USB audio control, which Linux shows as a mixer control named
89
+ `Sidetone`. To check yours:
90
+
91
+ ```sh
92
+ amixer -c <card number> scontrols | grep -i sidetone # card numbers: cat /proc/asound/cards
93
+ ```
94
+
95
+ | Headset | Sidetone slider | Source |
96
+ |---|---|---|
97
+ | Sony INZONE H6 Air (USB audio box) | works | tested |
98
+ | Sony INZONE H3, INZONE E9 | expected | same plain-USB-audio design as the H6 Air; untested |
99
+ | Corsair HS80, HS70 (wired), Virtuoso | reported to expose sidetone in alsamixer | [HeadsetControl README](https://github.com/Sapd/HeadsetControl) |
100
+
101
+ Headsets that set sidetone over a proprietary USB channel instead (many
102
+ SteelSeries Arctis, Logitech G and wireless Corsair models) do not show the
103
+ control; use [HeadsetControl](https://github.com/Sapd/HeadsetControl) for those.
104
+ Switching still works with them.
105
+
106
+ If your headset works, an issue or pull request adding it to the table is welcome.
107
+
108
+ ## Usage
109
+
110
+ ```sh
111
+ audioswitch # open the settings window (starts the tray app if needed)
112
+ audioswitch --hidden # start in the tray only
113
+ audioswitch --toggle # switch output now
114
+ ```
115
+
116
+ Closing the window keeps the app in the tray; quit from the tray menu.
117
+
118
+ ## How it works
119
+
120
+ - **Linux:** keys are read from evdev, so the hotkey works on Wayland and X11
121
+ alike. Switching sets the default sink, retargets every playing stream, and
122
+ rewires by hand any stream the session manager refuses to move.
123
+ - **Linux, KDE Plasma:** if the hotkey is the Volume Mute key, the app unassigns
124
+ Plasma's own Mute shortcut while it runs and mutes on a short tap itself.
125
+ Otherwise Plasma would mute the moment the key goes down and flicker during a
126
+ long hold. The shortcut is handed back when the app quits. On other desktops a
127
+ long hold of the mute key also toggles mute; pick a different key there.
128
+ - **Windows:** a low-level keyboard hook watches the key and swallows the mute
129
+ key so a long hold does not mute; a short tap is replayed so Windows mutes as
130
+ usual. The default device is changed through the same unofficial interface
131
+ other device switchers use (via [pycaw](https://github.com/AndreMiras/pycaw)).
132
+
133
+ Settings live in `~/.config/audioswitch/config.json` (Linux) or
134
+ `%APPDATA%\audioswitch\config.json` (Windows).
135
+
136
+ ## Releasing
137
+
138
+ Bump `version` in `pyproject.toml`, commit, then `git tag vX.Y.Z && git push --tags`.
139
+ The release workflow builds `audioswitch.exe` and creates the GitHub release; it
140
+ also publishes to PyPI and the AUR once those are enabled (see the comments in
141
+ [`workflow.yaml`](.github/workflows/workflow.yaml)).
142
+
143
+ ## License
144
+
145
+ MIT
@@ -0,0 +1,11 @@
1
+ audioswitch/__init__.py,sha256=vbhOZA8A68320VwH5XaQMswOcpwP7r-jAbfTIk7EmCk,41
2
+ audioswitch/__main__.py,sha256=JICx9XMLIAcBXz2INztt75ZQht3N7BNlbaD77OZcrM4,52
3
+ audioswitch/app.py,sha256=zdJdauj5tFhXrRNJpLMrcJWpX9hrW56hM46JtNIw8Gc,10340
4
+ audioswitch/icon.svg,sha256=Zpnov-ZSBjSkMU7BCAX5iDziZFpnzYsLLmPIEb7IfOw,470
5
+ audioswitch/linux.py,sha256=yBl0wMtNH7tK0y6k1rw74KxHlgPqGTozxPLCJ8rDHzQ,8249
6
+ audioswitch/windows.py,sha256=7VIeKOaoAe775YGzX67CNTQ7tMjHIrXGR_AFVIyC05s,7026
7
+ audioswitch-0.2.2.dist-info/METADATA,sha256=nBbUeVV4nkY3R1nUsNeWOaIv3koFodQQ7Lwvdi1Yz7c,6404
8
+ audioswitch-0.2.2.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
9
+ audioswitch-0.2.2.dist-info/entry_points.txt,sha256=4f1CjeMEPk-HhOmhdm9JEw7VCze18jpPvofQGd-3Oyo,49
10
+ audioswitch-0.2.2.dist-info/licenses/LICENSE,sha256=o0m66SIGJpomEnIwdnfWlFG4B7Gd0z9NQ3R6CcMtgCs,1064
11
+ audioswitch-0.2.2.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [gui_scripts]
2
+ audioswitch = audioswitch.app:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Richard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.