You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MacBook Air M1 Sonoma下pyautogui结合Arduino手势控制失效问题

问题解决:Mac Sonoma 14.0 M1上pyautogui无法触发全局媒体操作

核心问题分析

你的代码已能正确接收Arduino的手势数据,且已授予终端辅助功能权限,但pyautogui无法触发媒体操作,而shpotify能正常控制Spotify——这是因为shpotify直接调用Spotify的API,而pyautogui的按键模拟在Sonoma的权限机制和系统兼容性上存在限制。

解决方案步骤

1. 补全系统隐私权限

Sonoma对输入模拟的权限要求更严格,除了「辅助功能」,还需配置:

  • 打开「系统设置」->「隐私与安全」->「输入监控」
  • 勾选你运行代码的终端(如Terminal/iTerm)或Python IDE(如VS Code)
  • 重启终端/IDE,必要时重启系统让权限生效

2. 优化串口数据处理

原代码中str(ArduinoSerial.readline())会保留bytes类型的前缀(如b'Right\r\n'),可能导致匹配逻辑不稳定。改为直接解码字符串:

incoming = ArduinoSerial.readline().decode('utf-8').strip()

3. 替换pyautogui为系统原生osascript

pyautogui的媒体按键模拟在Sonoma上存在兼容性问题,改用osascript调用系统事件来触发全局媒体操作,这是更可靠的系统级方案:

修改后的完整代码:

import serial
import time
import os

ArduinoSerial = serial.Serial('/dev/cu.usbmodem11401', 9600)
time.sleep(2)

while True:
    incoming = ArduinoSerial.readline().decode('utf-8').strip()
    print(incoming)
    
    if 'Right' in incoming:
        # 下一曲
        os.system("osascript -e 'tell application \"System Events\" to key code 124'")
    if 'Left' in incoming:
        # 上一曲
        os.system("osascript -e 'tell application \"System Events\" to key code 123'")
    if 'Up' in incoming:
        # 音量加
        os.system("osascript -e 'tell application \"System Events\" to key code 144'")
    if 'Down' in incoming:
        # 音量减
        os.system("osascript -e 'tell application \"System Events\" to key code 142'")
    if 'Forward' in incoming:
        # 播放/暂停
        os.system("osascript -e 'tell application \"System Events\" to key code 127'")
    if 'Backward' in incoming:
        # 播放/暂停(可根据需求调整)
        os.system("osascript -e 'tell application \"System Events\" to key code 127'")

4. 验证效果

运行修改后的代码,测试手势触发:

  • 该方案通过系统原生事件模拟,可全局控制所有支持媒体快捷键的应用(如Safari、Music、VLC等)
  • 无需依赖特定应用的API,完全符合你控制所有媒体播放器的需求

内容的提问来源于stack exchange,提问作者Asfihani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 01:40:00