macOS 26下AppleScript获取Apple Music流媒体当前曲目失败求助
macOS 26下AppleScript获取流媒体当前播放曲目的解决办法
方案1:UI Scripting 抓取界面信息
Music应用的界面会实时展示当前播放的流媒体曲目,可通过System Events读取UI元素提取信息。前提:在「系统设置 > 隐私与安全性 > 辅助功能」中,给运行脚本的应用(如脚本编辑器、终端)开启权限。
示例脚本:
tell application "System Events" tell process "Music" try set trackDetails to {name:value of static text 1 of group 1 of group 1 of window "Music", artist:value of static text 2 of group 1 of group 1 of window "Music", album:value of static text 3 of group 1 of group 1 of window "Music"} display dialog "当前播放:" & trackDetails's name & " - " & trackDetails's artist & " (" & trackDetails's album & ")" on error errMsg display dialog "获取失败:" & errMsg end try end tell end tell
方案2:结合容错处理的混合调用
先尝试用原生current track获取已下载曲目信息,触发错误时自动切换到UI Scripting获取流媒体内容:
tell application "Music" if player state is playing then try set trackName to name of current track display dialog "当前播放:" & trackName on error tell application "System Events" tell process "Music" set trackName to value of static text 1 of group 1 of group 1 of window "Music" display dialog "当前播放(流媒体):" & trackName end tell end tell end try end if end tell
方案3:AppleScriptObjC调用系统框架
通过AppleScriptObjC直接调用MPNowPlayingInfoCenter获取播放信息,需确保应用有媒体访问权限(「系统设置 > 隐私与安全性 > 媒体与Apple Music」中开启):
use framework "MediaPlayer" use scripting additions set nowPlayingCenter to current application's MPNowPlayingInfoCenter's defaultCenter() set nowPlayingInfo to nowPlayingCenter's nowPlayingInfo() if nowPlayingInfo is not missing value then set trackName to nowPlayingInfo's objectForKey:"MPMediaItemPropertyTitle" as text set artistName to nowPlayingInfo's objectForKey:"MPMediaItemPropertyArtist" as text display dialog "当前播放:" & trackName & " - " & artistName else display dialog "未获取到播放信息" end if
内容的提问来源于stack exchange,提问作者Valeriya Pekar
相关产品推荐
相关产品推荐

