Python视频播放器脚本:实现macOS/Windows系统静音与通知禁用
Windows 平台实现方案
静音系统声音
使用pycaw库直接操控Windows音频会话,可精准静音除自身播放器外的其他系统声音:
- 安装依赖:
pip install pycaw - 核心代码:
from pycaw.pycaw import AudioUtilities, ISimpleAudioVolume def toggle_system_mute(mute: bool): sessions = AudioUtilities.GetAllSessions() for session in sessions: volume = session._ctl.QueryInterface(ISimpleAudioVolume) # 替换为你的播放器进程名,避免静音自身 if session.Process and session.Process.name() != "your_player.exe": volume.SetMute(mute, None)
播放前调用toggle_system_mute(True)静音,播放结束后调用toggle_system_mute(False)恢复。
禁用系统通知
通过winreg修改注册表临时关闭全局通知(需管理员权限):
import winreg def toggle_notifications(disable: bool): reg_path = r"SOFTWARE\Microsoft\Windows\CurrentVersion\Notifications\Settings" with winreg.OpenKey(winreg.HKEY_CURRENT_USER, reg_path, 0, winreg.KEY_WRITE) as reg_key: # 1=启用通知,0=禁用通知 winreg.SetValueEx(reg_key, "NOC_GLOBAL_SETTING_ALLOW_NOTIFICATIONS", 0, winreg.REG_DWORD, 0 if disable else 1)
修改后部分通知可能需要重启系统通知服务才会生效,播放前禁用、结束后恢复即可。
macOS 平台实现方案
静音系统声音
通过调用AppleScript实现全局静音,简单直接:
import subprocess def toggle_system_mute_mac(mute: bool): script = f"set volume output muted {'true' if mute else 'false'}" subprocess.run(["osascript", "-e", script], check=True)
若需仅静音非播放器进程,可通过pyobjc桥接AudioToolbox框架实现精准控制,安装依赖pip install pyobjc-core pyobjc-framework-AudioToolbox后可进一步扩展。
禁用系统通知
开启系统"勿扰模式",所有通知会暂存至后台,播放结束后恢复:
方式1:模拟GUI操作(无需重启服务)
import subprocess def toggle_do_not_disturb(enable: bool): script = f""" tell application "System Events" tell process "SystemUIServer" set nc_menu to menu bar item "Notification Center" of menu bar 1 click nc_menu {'click menu item "Turn On Do Not Disturb" of menu of nc_menu' if enable else 'click menu item "Turn Off Do Not Disturb" of menu of nc_menu'} end tell end tell """ subprocess.run(["osascript", "-e", script], check=True)
方式2:修改系统配置(需重启通知中心,更稳定)
import subprocess def toggle_do_not_disturb(enable: bool): state = "on" if enable else "off" subprocess.run(["defaults", "write", "com.apple.notificationcenterui", "doNotDisturb", "-bool", state], check=True) subprocess.run(["killall", "NotificationCenter"], check=True)
内容的提问来源于stack exchange,提问作者mrrockkz
相关产品推荐
相关产品推荐

