Skip to content

Instantly share code, notes, and snippets.

@qianlifeng
Last active September 6, 2026 03:00
Show Gist options
  • Select an option

  • Save qianlifeng/bb270f4d9d36053d6750244445e5bfc9 to your computer and use it in GitHub Desktop.

Select an option

Save qianlifeng/bb270f4d9d36053d6750244445e5bfc9 to your computer and use it in GitHub Desktop.
Wox.Plugin.Script.SoundSwitch
#!/usr/bin/env python3
# {
# "Id": "a7f3b2c1-9d4e-4f6a-8b2c-1e5d9a3f7b24",
# "Name": "i18n:plugin_name",
# "Author": "qianlifeng",
# "Version": "1.0.4",
# "MinWoxVersion": "2.0.0",
# "Description": "i18n:plugin_description",
# "Icon": "emoji:🔊",
# "TriggerKeywords": ["sound"],
# "SupportedOS": ["windows", "darwin"],
# "Commands": [
# { "Command": "output", "Description": "i18n:cmd_output" },
# { "Command": "input", "Description": "i18n:cmd_input" }
# ],
# "Features": [
# { "Name": "debounce", "Params": { "IntervalMs": 200 } },
# { "Name": "ignoreAutoScore" }
# ],
# "I18n": {
# "en_US": {
# "plugin_name": "Sound Switch",
# "plugin_description": "Switch audio input and output devices quickly",
# "cmd_output": "Browse and switch output devices",
# "cmd_input": "Browse and switch input devices",
# "menu_output": "Output devices",
# "menu_output_sub": "Switch speakers or headphones",
# "menu_input": "Input devices",
# "menu_input_sub": "Switch microphones",
# "hint_commands": "output • input",
# "current": "Current",
# "comm_tag": "Communication",
# "action_switch": "Switch to this device",
# "action_set_comm": "Set as communication device",
# "action_copy": "Copy name",
# "action_refresh": "Refresh",
# "empty_devices": "No audio devices found",
# "empty_devices_sub": "Check your audio drivers",
# "downloading_cli": "Downloading audio CLI...",
# "downloading_cli_sub": "Needed once for Windows audio control",
# "missing_cli": "Audio CLI not available",
# "missing_cli_sub": "win-audio-cli will be downloaded automatically on first use"
# },
# "zh_CN": {
# "plugin_name": "声音切换",
# "plugin_description": "快速切换音频输入和输出设备",
# "cmd_output": "浏览并切换输出设备",
# "cmd_input": "浏览并切换输入设备",
# "menu_output": "输出设备",
# "menu_output_sub": "切换扬声器或耳机",
# "menu_input": "输入设备",
# "menu_input_sub": "切换麦克风",
# "hint_commands": "output • input",
# "current": "当前",
# "comm_tag": "通信",
# "action_switch": "切换到此设备",
# "action_set_comm": "设为通信设备",
# "action_copy": "复制名称",
# "action_refresh": "刷新",
# "empty_devices": "未找到音频设备",
# "empty_devices_sub": "请检查音频驱动",
# "downloading_cli": "正在下载音频 CLI...",
# "downloading_cli_sub": "Windows 音频控制只需下载一次",
# "missing_cli": "音频 CLI 不可用",
# "missing_cli_sub": "首次使用时会自动下载 win-audio-cli"
# }
# }
# }
"""
Wox Sound Switch script plugin.
Switch audio input and output devices quickly.
Windows uses win-audio-cli; macOS uses SwitchAudioSource when available.
"""
from __future__ import annotations
import datetime
import hashlib
import json
import locale
import os
import shutil
import ssl
import subprocess
import sys
import urllib.request
from typing import Any, List, Literal, TypedDict
IOType = Literal["input", "output"]
COMMANDS = ("output", "input")
WIN_CLI_VERSION = "1.3.1"
WIN_CLI_URL = (
f"https://github.com/Inovvia/go-win-audio-cli/releases/download/"
f"{WIN_CLI_VERSION}/win-audio-cli.exe"
)
WIN_CLI_SHA256 = "9bda285caea2477f5504a73b532d4102e5d8e37a63c16669faca1834ccfd2048"
CREATE_NO_WINDOW = 0x08000000
PLUGIN_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><defs><linearGradient id=\"ssBg\" x1=\"8\" y1=\"4\" "
"x2=\"40\" y2=\"46\" gradientUnits=\"userSpaceOnUse\"><stop stop-color=\"#8b5cf6\"/>"
"<stop offset=\".5\" stop-color=\"#ec4899\"/><stop offset=\"1\" stop-color=\"#f97316\"/>"
"</linearGradient></defs><rect width=\"48\" height=\"48\" rx=\"13\" fill=\"url(#ssBg)\"/>"
"<path d=\"M14 20h4l6-8v24l-6-8h-4a2 2 0 0 1-2-2V22a2 2 0 0 1 2-2z\" fill=\"#fff\"/>"
"<path d=\"M30 18a8 8 0 0 1 0 12\" fill=\"none\" stroke=\"#fde68a\" stroke-width=\"2.8\" "
"stroke-linecap=\"round\"/><path d=\"M34 14a14 14 0 0 1 0 20\" fill=\"none\" "
"stroke=\"#fef3c7\" stroke-width=\"2.4\" stroke-linecap=\"round\"/></svg>"
)
OUTPUT_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#3b82f6\"/>"
"<path d=\"M14 20h4l6-8v24l-6-8h-4a2 2 0 0 1-2-2V22a2 2 0 0 1 2-2z\" fill=\"#fff\"/>"
"<path d=\"M30 18a7 7 0 0 1 0 12\" fill=\"none\" stroke=\"#fde68a\" "
"stroke-width=\"2.6\" stroke-linecap=\"round\"/></svg>"
)
INPUT_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#ef4444\"/>"
"<rect x=\"20\" y=\"12\" width=\"8\" height=\"14\" rx=\"4\" fill=\"#fff\"/>"
"<path d=\"M16 26a8 8 0 0 0 16 0M24 34v4\" fill=\"none\" stroke=\"#fff\" "
"stroke-width=\"2.8\" stroke-linecap=\"round\"/></svg>"
)
CHECK_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#16a34a\"/>"
"<path d=\"M15 25l6 6 13-14\" fill=\"none\" stroke=\"#fff\" stroke-width=\"3.2\" "
"stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>"
)
COMM_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#14b8a6\"/>"
"<path d=\"M20 18h8a4 4 0 0 1 4 4v6a4 4 0 0 1-4 4h-2l-4 4v-4h-2a4 4 0 0 1-4-4v-6a4 4 0 0 1 4-4z\" "
"fill=\"#fff\"/></svg>"
)
COPY_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"80\" height=\"80\" "
"viewBox=\"0 0 80 80\"><g fill=\"none\"><path fill=\"#f2c94c\" fill-rule=\"evenodd\" "
"d=\"M30 55V39.57a4 4 0 0 1 1.158-2.816l10.47-10.568a4 4 0 0 1 2.84-1.185H50v-8a4 "
"4 0 0 0-4-4h-8.19L22 13a4 4 0 0 0-4 4v34a4 4 0 0 0 4 4z\" clip-rule=\"evenodd\"/>"
"<path fill=\"#f2994a\" fill-rule=\"evenodd\" d=\"M41.73 26.087a4 4 0 0 1 2.739-1.085"
"L57.999 25A4 4 0 0 1 62 29v34a4 4 0 0 1-4 4H34a4 4 0 0 1-4-4V39.57a4 4 0 0 1 "
"1.08-2.734a.667.667 0 0 0 .52 1.086h7.2a4 4 0 0 0 4-4v-7.308a.665.665 0 0 0-1.07"
"-.527\" clip-rule=\"evenodd\"/><path fill=\"#f2f2f2\" d=\"m31.126 36.785l10.537-10.64"
"a.665.665 0 0 1 1.137.468v7.308a4 4 0 0 1-4 4h-7.2a.667.667 0 0 1-.474-1.136\"/>"
"</g></svg>"
)
REFRESH_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#2563eb\"/>"
"<path d=\"M16 20a9 9 0 0 1 16 3M32 28a9 9 0 0 1-16-3\" fill=\"none\" stroke=\"#fff\" "
"stroke-width=\"2.8\" stroke-linecap=\"round\"/>"
"<path d=\"M16 14v7h7M32 34v-7h-7\" fill=\"none\" stroke=\"#fbbf24\" "
"stroke-width=\"2.6\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>"
)
HEADPHONES_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#a855f7\"/>"
"<path d=\"M16 26v6a2 2 0 0 0 2 2h2v-12h-2a2 2 0 0 0-2 2zM32 26v6a2 2 0 0 1-2 2h-2v-12h2a2 2 0 0 1 2 2z\" "
"fill=\"#fff\"/><path d=\"M18 22h12\" stroke=\"#fde68a\" stroke-width=\"2.4\" "
"stroke-linecap=\"round\"/></svg>"
)
BLUETOOTH_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#2563eb\"/>"
"<path d=\"M22 14l8 8-6 6 6 6-8 8V14zM22 26v-4l4-4-4-4\" fill=\"none\" stroke=\"#fff\" "
"stroke-width=\"2.6\" stroke-linejoin=\"round\"/></svg>"
)
HDMI_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><rect x=\"8\" y=\"14\" width=\"32\" height=\"20\" rx=\"3\" "
"fill=\"#1e293b\"/><rect x=\"12\" y=\"18\" width=\"24\" height=\"12\" rx=\"1\" "
"fill=\"#38bdf8\"/><path d=\"M20 34h8v4h-8z\" fill=\"#64748b\"/></svg>"
)
USB_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#059669\"/>"
"<path d=\"M24 12v8M20 16h8M22 20h4v6h-4zM18 28h12v8H18z\" fill=\"none\" "
"stroke=\"#fff\" stroke-width=\"2.4\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>"
"</svg>"
)
SPEAKER_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><circle cx=\"24\" cy=\"24\" r=\"20\" fill=\"#f59e0b\"/>"
"<path d=\"M16 20h3l5-6v20l-5-6h-3a2 2 0 0 1-2-2V22a2 2 0 0 1 2-2z\" fill=\"#fff\"/>"
"</svg>"
)
WARN_ICON = (
"svg:<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"48\" height=\"48\" "
"viewBox=\"0 0 48 48\"><path d=\"M24 8l18 32H6z\" fill=\"#f59e0b\"/>"
"<path d=\"M24 20v10\" stroke=\"#fff\" stroke-width=\"3.2\" stroke-linecap=\"round\"/>"
"<circle cx=\"24\" cy=\"35\" r=\"2.1\" fill=\"#fff\"/></svg>"
)
TRANSPORT_LABELS = {
"hdmi": "HDMI",
"displayport": "DisplayPort",
"usb": "USB Audio",
"bluetooth": "Bluetooth",
"headphones": "Headphones",
"microphone": "Microphone",
"speakers": "Speakers",
"spdif": "Digital (SPDIF)",
"virtual": "Virtual Device",
"builtin": "Built-in",
}
class WoxPluginBase:
"""Wox plugin base class for script plugins. Do not modify this class."""
class Preview(TypedDict, total=False):
preview_type: str
preview_data: str
preview_properties: dict[str, str]
class ActionItem(TypedDict, total=False):
id: str
name: str
icon: str
text: str
url: str
path: str
message: str
query: str
preventHideAfterAction: bool
data: dict[str, str]
class TailItem(TypedDict, total=False):
id: str
type: str
text: str
image: str
contextData: dict[str, str]
class QueryResult(TypedDict, total=False):
title: str
subtitle: str
icon: str
preview: WoxPluginBase.Preview
tails: List[WoxPluginBase.TailItem]
score: int
actions: List[WoxPluginBase.ActionItem]
def __init__(self):
self.log_file_path = __file__ + ".log"
def log(self, message: str) -> None:
ts = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
message = f"[{ts}] {message}"
if self.is_invoke_from_wox():
with open(self.log_file_path, "a", encoding="utf-8") as handle:
handle.write(f"{message}\n")
else:
print(f"LOG: {message}")
def is_invoke_from_wox(self) -> bool:
return "WOX_PLUGIN_ID" in os.environ
def _build_response(self, result: Any, request_id: Any) -> dict:
return {"jsonrpc": "2.0", "result": result, "id": request_id}
def _build_error_response(
self, code: int, message: str, data: Any = None, request_id: Any = None
) -> dict:
error = {"code": code, "message": message}
if data is not None:
error["data"] = data
return {"jsonrpc": "2.0", "error": error, "id": request_id}
def query(
self, raw_query: str, trigger_keyword: str, command: str, search: str
) -> List[WoxPluginBase.QueryResult]:
return []
def action(self, action_id: str, data: Any) -> None:
return None
def handle_query(self, params, request_id):
results = self.query(
params.get("raw_query", ""),
params.get("trigger_keyword", ""),
params.get("command", ""),
params.get("search", ""),
)
return self._build_response({"items": results}, request_id)
def handle_action(self, params, request_id):
self.action(params.get("id", ""), params.get("data", ""))
return self._build_response({}, request_id)
def run(self):
if hasattr(sys.stdout, "reconfigure"):
try:
sys.stdout.reconfigure(encoding="utf-8")
except Exception:
pass
if self.is_invoke_from_wox():
try:
stdin_text = sys.stdin.read()
except Exception:
return 1
else:
print("Manual mode - please enter query:")
query_input = input()
stdin_text = (
'{"jsonrpc": "2.0", "method": "query", "params": {"search": "'
+ query_input.replace("\\", "\\\\").replace('"', '\\"')
+ '"}, "id": 1}'
)
try:
request = json.loads(stdin_text)
except json.JSONDecodeError as exc:
print(
json.dumps(
self._build_error_response(-32700, "Parse error", str(exc), None),
ensure_ascii=False,
)
)
return 1
if request.get("jsonrpc") != "2.0":
print(
json.dumps(
self._build_error_response(
-32600, "Invalid Request", None, request.get("id")
),
ensure_ascii=False,
)
)
return 1
method = request.get("method")
params = request.get("params", {})
request_id = request.get("id")
if method == "query":
response = self.handle_query(params, request_id)
elif method == "action":
response = self.handle_action(params, request_id)
else:
response = self._build_error_response(
-32601,
"Method not found",
f"Method '{method}' not supported",
request_id,
)
print(json.dumps(response, ensure_ascii=False))
return 0
class AudioDevice(TypedDict, total=False):
id: str
uid: str
name: str
is_input: bool
is_output: bool
transport_type: str
is_default: bool
is_communication: bool
def _plugin_data_dir() -> str:
base = os.environ.get("WOX_DIRECTORY_USER_DATA") or os.path.join(
os.path.expanduser("~"), ".wox", "wox-user"
)
path = os.path.join(base, "cache", "soundswitch-script-plugin")
os.makedirs(path, exist_ok=True)
return path
def _no_window_kwargs() -> dict[str, Any]:
if os.name != "nt":
return {}
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = 0
return {
"creationflags": getattr(subprocess, "CREATE_NO_WINDOW", CREATE_NO_WINDOW),
"startupinfo": startupinfo,
}
def _as_data_map(data: Any) -> dict[str, str]:
if isinstance(data, str) and data.strip():
try:
data = json.loads(data)
except json.JSONDecodeError:
return {}
if isinstance(data, dict):
return {str(key): str(value) for key, value in data.items()}
return {}
def _command_query(trigger: str, command: str, search: str = "") -> str:
search = (search or "").strip()
if search:
return f"{trigger} {command} {search}"
return f"{trigger} {command} "
def _map_transport(name: str) -> str:
lower = name.lower()
rules = (
("realtek digital", "spdif"),
("digital output", "spdif"),
("steam streaming", "virtual"),
("nvidia", "hdmi"),
("headphones", "headphones"),
("headset", "headphones"),
("airpods", "headphones"),
("microphone", "microphone"),
("speakers", "speakers"),
("hdmi", "hdmi"),
("displayport", "displayport"),
("usb", "usb"),
("bluetooth", "bluetooth"),
(" mic", "microphone"),
("speaker", "speakers"),
("spdif", "spdif"),
("optical", "spdif"),
("virtual", "virtual"),
)
for needle, value in rules:
if needle in lower:
return value
return "speakers"
def _device_icon(device: AudioDevice, is_current: bool) -> str:
transport = str(device.get("transport_type") or "")
name = str(device.get("name") or "").lower()
if transport in {"headphones"} or "airpod" in name or "headphone" in name:
return HEADPHONES_ICON
if transport == "bluetooth":
return BLUETOOTH_ICON
if transport in {"hdmi", "displayport"}:
return HDMI_ICON
if transport == "usb":
return USB_ICON
if device.get("is_input"):
return INPUT_ICON if not is_current else CHECK_ICON
return SPEAKER_ICON if not is_current else CHECK_ICON
def _transport_label(device: AudioDevice) -> str:
transport = str(device.get("transport_type") or "")
return TRANSPORT_LABELS.get(transport, transport.capitalize() if transport else "")
def _match_score(needle: str, name: str) -> int:
if not needle:
return 80
lower = name.lower()
if lower == needle:
return 300
if lower.startswith(needle):
return 250
if needle in lower:
return 180
return 0
class WindowsAudioBackend:
def __init__(self) -> None:
self._cli = ""
def _cached_cli(self) -> str:
return os.path.join(_plugin_data_dir(), "cli", "win-audio-cli.exe")
def _resolve_cli(self) -> str:
if self._cli:
return self._cli
found = shutil.which("win-audio-cli") or shutil.which("win-audio-cli.exe")
if found:
self._cli = found
return self._cli
cached = self._cached_cli()
if os.path.isfile(cached):
self._cli = cached
return self._cli
return ""
def _sha256(self, path: str) -> str:
digest = hashlib.sha256()
with open(path, "rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def _download_cli(self) -> None:
dest = self._cached_cli()
os.makedirs(os.path.dirname(dest), exist_ok=True)
tmp = dest + ".part"
request = urllib.request.Request(
WIN_CLI_URL,
headers={"User-Agent": "Wox.Plugin.Script.SoundSwitch/1.0"},
)
context = ssl.create_default_context()
with urllib.request.urlopen(request, timeout=120, context=context) as response:
with open(tmp, "wb") as handle:
shutil.copyfileobj(response, handle)
if self._sha256(tmp).lower() != WIN_CLI_SHA256.lower():
os.remove(tmp)
raise RuntimeError("Downloaded CLI checksum mismatch")
os.replace(tmp, dest)
def ensure_cli(self) -> str:
cli = self._resolve_cli()
if cli:
return cli
self._download_cli()
cli = self._cached_cli()
if not os.path.isfile(cli):
raise RuntimeError("Failed to prepare win-audio-cli")
self._cli = cli
return cli
def cli_ready(self) -> bool:
return bool(self._resolve_cli())
def prepare_cli_async(self) -> bool:
if self.cli_ready():
return False
lock = os.path.join(_plugin_data_dir(), "cli.downloading")
try:
fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY)
os.close(fd)
except FileExistsError:
return True
_spawn_worker("download-cli")
return True
def _run(self, args: list[str]) -> Any:
cli = self.ensure_cli()
result = subprocess.run(
[cli, *args],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=20,
**_no_window_kwargs(),
)
if result.returncode != 0:
message = (result.stderr or result.stdout or "CLI failed").strip()
raise RuntimeError(message.splitlines()[-1][:240] if message else "CLI failed")
stdout = (result.stdout or "").strip()
if not stdout:
return {}
return json.loads(stdout)
def _map_device(self, raw: dict[str, Any], io_type: IOType) -> AudioDevice:
name = str(raw.get("name") or "")
device_id = str(raw.get("id") or "")
return {
"id": device_id,
"uid": device_id,
"name": name,
"is_input": io_type == "input",
"is_output": io_type == "output",
"transport_type": _map_transport(name),
"is_default": bool(raw.get("isDefault")),
"is_communication": bool(raw.get("isDefaultCom")),
}
def list_devices(self) -> tuple[list[AudioDevice], list[AudioDevice]]:
payload = self._run(["list", "--json"])
outputs = [
self._map_device(item, "output")
for item in payload.get("outputs") or []
if isinstance(item, dict)
]
inputs = [
self._map_device(item, "input")
for item in payload.get("inputs") or []
if isinstance(item, dict)
]
return outputs, inputs
def get_default(self, io_type: IOType) -> AudioDevice:
outputs, inputs = self.list_devices()
devices = inputs if io_type == "input" else outputs
for device in devices:
if device.get("is_default"):
return device
if devices:
return devices[0]
raise RuntimeError(f"No {io_type} device found")
def switch(self, io_type: IOType, device_id: str) -> None:
cmd = "switch-input" if io_type == "input" else "switch-output"
self._run([cmd, "--id", device_id])
def switch_comm(self, io_type: IOType, device_id: str) -> None:
cmd = (
"switch-input-communication"
if io_type == "input"
else "switch-output-communication"
)
self._run([cmd, "--id", device_id])
class MacOSAudioBackend:
def __init__(self) -> None:
self._switch = shutil.which("SwitchAudioSource") or shutil.which("switchaudiosource")
def _require(self) -> str:
if not self._switch:
raise RuntimeError(
"Install SwitchAudioSource (brew install switchaudio-osx) for macOS support"
)
return self._switch
def _run(self, args: list[str]) -> str:
tool = self._require()
result = subprocess.run(
[tool, *args],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
timeout=15,
)
if result.returncode != 0:
message = (result.stderr or result.stdout or "SwitchAudioSource failed").strip()
raise RuntimeError(message.splitlines()[-1][:240] if message else "Command failed")
return (result.stdout or "").strip()
def _list_raw(self, io_type: IOType) -> list[str]:
flag = "-t" if io_type == "input" else ""
args = ["-a"]
if flag:
args.append(flag)
text = self._run(args)
return [line.strip() for line in text.splitlines() if line.strip()]
def _current_name(self, io_type: IOType) -> str:
args = ["-c"]
if io_type == "input":
args = ["-t", "input", "-c"]
return self._run(args)
def list_devices(self) -> tuple[list[AudioDevice], list[AudioDevice]]:
outputs: list[AudioDevice] = []
inputs: list[AudioDevice] = []
current_out = self._current_name("output")
current_in = self._current_name("input")
for index, name in enumerate(self._list_raw("output")):
outputs.append(
{
"id": name,
"uid": name,
"name": name,
"is_input": False,
"is_output": True,
"transport_type": _map_transport(name),
"is_default": name == current_out,
"is_communication": False,
}
)
for index, name in enumerate(self._list_raw("input")):
inputs.append(
{
"id": name,
"uid": name,
"name": name,
"is_input": True,
"is_output": False,
"transport_type": _map_transport(name),
"is_default": name == current_in,
"is_communication": False,
}
)
return outputs, inputs
def get_default(self, io_type: IOType) -> AudioDevice:
name = self._current_name(io_type)
outputs, inputs = self.list_devices()
devices = inputs if io_type == "input" else outputs
for device in devices:
if device["name"] == name:
return device
raise RuntimeError(f"No {io_type} device found")
def switch(self, io_type: IOType, device_id: str) -> None:
args = ["-s", device_id]
if io_type == "input":
args = ["-t", "input", "-s", device_id]
self._run(args)
def switch_comm(self, io_type: IOType, device_id: str) -> None:
self.switch(io_type, device_id)
def _backend() -> WindowsAudioBackend | MacOSAudioBackend:
if sys.platform == "win32":
return WindowsAudioBackend()
if sys.platform == "darwin":
return MacOSAudioBackend()
raise RuntimeError("Unsupported platform")
def _ensure_backend_ready() -> WoxPluginBase.QueryResult | None:
backend = _backend()
if sys.platform == "win32" and isinstance(backend, WindowsAudioBackend):
if backend.cli_ready():
return None
backend.prepare_cli_async()
return {
"title": "i18n:downloading_cli",
"subtitle": "i18n:downloading_cli_sub",
"icon": PLUGIN_ICON,
"score": 100,
"actions": [
{
"name": "i18n:action_refresh",
"id": "change-query",
"icon": REFRESH_ICON,
"query": "sound output ",
"preventHideAfterAction": True,
}
],
}
return None
def _sort_devices(devices: list[AudioDevice], current_uid: str) -> list[AudioDevice]:
current = next((d for d in devices if d.get("uid") == current_uid), None)
rest = sorted(
[d for d in devices if d.get("uid") != current_uid],
key=lambda item: str(item.get("name") or "").lower(),
)
return ([current] if current else []) + rest
def _spawn_worker(mode: str) -> None:
script = os.path.abspath(__file__)
kwargs: dict[str, Any] = {
"stdin": subprocess.DEVNULL,
"stdout": subprocess.DEVNULL,
"stderr": subprocess.DEVNULL,
"close_fds": True,
**_no_window_kwargs(),
}
if os.name != "nt":
kwargs["start_new_session"] = True
python = sys.executable
if os.name == "nt" and python.lower().endswith("python.exe"):
pythonw = os.path.join(os.path.dirname(python), "pythonw.exe")
if os.path.isfile(pythonw):
python = pythonw
subprocess.Popen([python, script, f"--worker-{mode}"], **kwargs)
class SoundSwitchPlugin(WoxPluginBase):
def query(
self, raw_query: str, trigger_keyword: str, command: str, search: str
) -> List[WoxPluginBase.QueryResult]:
trigger = trigger_keyword or "sound"
command, search = self._normalize(command, search)
try:
if command == "output":
return self._device_results(trigger, "output", search)
if command == "input":
return self._device_results(trigger, "input", search)
return self._menu_results(trigger, search)
except RuntimeError as exc:
message = str(exc)
if "download" in message.lower() or "cli" in message.lower():
return [
{
"title": "i18n:missing_cli",
"subtitle": message or "i18n:missing_cli_sub",
"icon": WARN_ICON,
"score": 100,
}
]
return [
{
"title": message,
"subtitle": "i18n:hint_commands",
"icon": WARN_ICON,
"score": 100,
}
]
def action(self, action_id: str, data: Any) -> None:
payload = _as_data_map(data)
backend = _backend()
try:
if action_id == "ss-switch":
io_type = payload.get("io_type", "output")
device_id = payload.get("device_id", "")
backend.switch(io_type, device_id)
elif action_id == "ss-set-comm":
backend.switch_comm(payload.get("io_type", "output"), payload.get("device_id", ""))
except Exception as exc:
self.log(str(exc))
def _normalize(self, command: str, search: str) -> tuple[str, str]:
command = (command or "").strip().lower()
search = (search or "").strip()
if command in COMMANDS:
return command, search
return "", search
def _menu_results(self, trigger: str, search: str) -> List[WoxPluginBase.QueryResult]:
needle = search.lower()
entries = (
("output", "i18n:menu_output", "i18n:menu_output_sub", OUTPUT_ICON, 110),
("input", "i18n:menu_input", "i18n:menu_input_sub", INPUT_ICON, 100),
)
items: List[WoxPluginBase.QueryResult] = []
for name, title, subtitle, icon, base in entries:
if needle and needle not in name and needle not in title.lower():
continue
items.append(
{
"title": title if not needle else name,
"subtitle": subtitle,
"icon": icon,
"score": 300 if name == needle else base,
"actions": [
{
"name": title,
"id": "change-query",
"icon": icon,
"query": _command_query(trigger, name),
"preventHideAfterAction": True,
}
],
}
)
if not items:
return [
{
"title": "Sound Switch",
"subtitle": "i18n:hint_commands",
"icon": PLUGIN_ICON,
"score": 100,
}
]
return items
def _device_results(
self, trigger: str, io_type: IOType, search: str
) -> List[WoxPluginBase.QueryResult]:
pending = _ensure_backend_ready()
if pending:
pending["actions"][0]["query"] = _command_query(trigger, io_type, search)
return [pending]
backend = _backend()
outputs, inputs = backend.list_devices()
devices = inputs if io_type == "input" else outputs
current = backend.get_default(io_type)
current_uid = str(current.get("uid") or "")
needle = search.lower()
sorted_devices = _sort_devices(devices, current_uid)
visible = sorted_devices
if needle:
visible = [
d for d in visible if needle in str(d.get("name") or "").lower()
]
if not visible:
return [
{
"title": "i18n:empty_devices",
"subtitle": "i18n:empty_devices_sub",
"icon": WARN_ICON,
"score": 50,
}
]
results: List[WoxPluginBase.QueryResult] = []
base_icon = INPUT_ICON if io_type == "input" else OUTPUT_ICON
for index, device in enumerate(visible):
uid = str(device.get("uid") or "")
device_id = str(device.get("id") or "")
name = str(device.get("name") or "")
is_current = uid == current_uid
subtitle_parts: list[str] = []
label = _transport_label(device)
if label:
subtitle_parts.append(label)
if is_current:
subtitle_parts.append("i18n:current")
if device.get("is_communication"):
subtitle_parts.append("i18n:comm_tag")
tails: List[WoxPluginBase.TailItem] = []
if is_current:
tails.append({"type": "text", "text": "ON"})
actions: List[WoxPluginBase.ActionItem] = []
if not is_current:
actions.append(
{
"name": "i18n:action_switch",
"id": "ss-switch",
"icon": CHECK_ICON,
"data": {"io_type": io_type, "device_id": device_id},
}
)
if sys.platform == "win32":
actions.append(
{
"name": "i18n:action_set_comm",
"id": "ss-set-comm",
"icon": COMM_ICON,
"data": {"io_type": io_type, "device_id": device_id},
}
)
actions.append(
{
"name": "i18n:action_copy",
"id": "copy-to-clipboard",
"icon": COPY_ICON,
"text": name,
}
)
results.append(
{
"title": ("• " if is_current else "") + name,
"subtitle": " • ".join(subtitle_parts) or base_icon,
"icon": _device_icon(device, is_current),
"score": 200 - index + (50 if is_current else 0),
"tails": tails,
"actions": actions,
}
)
return results
def _worker_download_cli() -> int:
lock = os.path.join(_plugin_data_dir(), "cli.downloading")
try:
WindowsAudioBackend().ensure_cli()
return 0
except Exception:
return 1
finally:
try:
if os.path.isfile(lock):
os.remove(lock)
except OSError:
pass
def _dispatch_worker(argv: list[str]) -> int | None:
if len(argv) < 2:
return None
if argv[1] == "--worker-download-cli":
return _worker_download_cli()
return None
if __name__ == "__main__":
worker_code = _dispatch_worker(sys.argv)
if worker_code is not None:
sys.exit(worker_code)
sys.exit(SoundSwitchPlugin().run())
@qianlifeng

qianlifeng commented Sep 2, 2026 •

Copy link
Copy Markdown
Author
image

@qianlifeng

Copy link
Copy Markdown
Author
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment