# -*- coding: utf-8 -*- r'''把音效功能接进协议层和服务端。 加两条命令: sfx_list 列出可用音效 sfx_play 播放指定的音效 复用现成的 play_audio(MCI),不另造一套播放器。 ''' from __future__ import annotations import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent PROTO = ROOT / "windows" / "lanremote" / "protocol.py" SERVER = ROOT / "windows" / "lanremote" / "server.py" def load(p: Path): raw = p.read_bytes() return raw.startswith(b"\xef\xbb\xbf"), raw.decode("utf-8-sig") def save(p: Path, text: str, bom: bool): p.write_bytes((b"\xef\xbb\xbf" if bom else b"") + text.encode("utf-8")) # ---------------------------------------------------------------- protocol PROTO_ANCHOR = 'CMD_AUDIO_LIST = "audio_list"' PROTO_NEW = '''CMD_AUDIO_LIST = "audio_list" CMD_SFX_LIST = "sfx_list" # 列出可用音效(内置 + 用户自己放的) CMD_SFX_PLAY = "sfx_play" # 播放某个音效''' # ---------------------------------------------------------------- server # 挂在 CMD_AUDIO_LIST 那条分支后面 SERVER_ANCHOR = ''' if cmd == P.CMD_AUDIO_LIST:''' SERVER_NEW = ''' if cmd == P.CMD_SFX_LIST: items = self.actions.list_sfx() return {"ok": True, "sfx": items, "count": len(items), "dir": self.actions.sfx_dir_hint()} if cmd == P.CMD_SFX_PLAY: name = str(body.get("name") or "").strip() if not name: return {"ok": False, "error": "没说要放哪个音效"} try: msg = self.actions.play_sfx(name) except Exception as exc: # noqa: BLE001 return {"ok": False, "error": str(exc)} return {"ok": True, "message": msg, "name": name} ''' + SERVER_ANCHOR def main() -> int: ok = True bom, text = load(PROTO) if "CMD_SFX_LIST" in text: print(" · protocol.py 已经加过了") elif PROTO_ANCHOR not in text: print(" ✗ protocol.py 找不到锚点") ok = False else: text = text.replace(PROTO_ANCHOR, PROTO_NEW, 1) save(PROTO, text, bom) print(" ✓ protocol.py 加了两条命令") bom, text = load(SERVER) if "CMD_SFX_LIST" in text: print(" · server.py 已经加过了") elif SERVER_ANCHOR not in text: print(" ✗ server.py 找不到锚点") ok = False else: text = text.replace(SERVER_ANCHOR, SERVER_NEW, 1) save(SERVER, text, bom) print(" ✓ server.py 加了两个处理分支") return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())