Files
lyroc/backend/modules/apple_music.py
2025-05-27 14:16:48 +08:00

119 lines
3.7 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
Apple Music 控制和状态获取模块
负责与 Apple Music 应用交互的所有功能
"""
import subprocess
import logging
logger = logging.getLogger(__name__)
def run_applescript(script: str):
"""运行 AppleScript 并返回结果"""
result = subprocess.run([
"osascript", "-e", script
], capture_output=True, text=True)
return result.stdout.strip()
def get_music_status():
"""获取 Apple Music 播放状态"""
script = '''
tell application "Music"
if it is running then
set playerState to (get player state) as string
if playerState is "stopped" then
return "stopped"
else
set trackName to name of current track
set artistName to artist of current track
set pos to player position
set dur to duration of current track
return playerState & "|||" & trackName & "|||" & artistName & "|||" & (pos as text) & "|||" & (dur as text)
end if
else
return "notrunning"
end if
end tell
'''
try:
out = run_applescript(script)
if out is None:
logger.error("AppleScript执行失败返回了None")
return {"status": "error", "error": "AppleScript execution failed"}
if out == "notrunning":
return {"status": "notrunning"}
if out == "stopped":
return {"status": "stopped"}
try:
player_state, track_name, artist, pos, dur = out.split("|||")
return {
"status": player_state,
"track_name": track_name,
"artist": artist,
"position": float(pos),
"duration": float(dur)
}
except Exception as e:
return {"status": "error", "error": str(e), "raw": out}
except Exception as e:
logger.error(f"获取音乐状态时发生异常: {e}")
return {"status": "error", "error": str(e)}
def control_music(action, position=None):
"""控制Apple Music播放"""
try:
if action == "playpause":
script = '''
tell application "Music"
if it is running then
playpause
return "ok"
else
return "notrunning"
end if
end tell
'''
elif action == "previous":
script = '''
tell application "Music"
if it is running then
previous track
return "ok"
else
return "notrunning"
end if
end tell
'''
elif action == "next":
script = '''
tell application "Music"
if it is running then
next track
return "ok"
else
return "notrunning"
end if
end tell
'''
elif action == "seek" and position is not None:
script = f'''
tell application "Music"
if it is running then
set player position to {position}
return "ok"
else
return "notrunning"
end if
end tell
'''
else:
return {"status": "error", "message": "未知的命令"}
result = run_applescript(script)
if result == "ok":
return {"status": "success"}
else:
return {"status": "error", "message": result}
except Exception as e:
return {"status": "error", "message": str(e)}