用于控制iTunes和Radio的Applescript

时间:2011-09-09 19:30:30

标签: applescript itunes rdio

我有一个与 Alfred 结合使用的Applescript,可播放或暂停iTunes中的当前曲目或 Rdio ,具体取决于哪个我打开了。在我的脚本中,Rdio优先,因为我总是打开iTunes,只在我需要它时才打开Rdio。

通常,当轨道在iTunes中播放并且我点击我的全局快捷方式来运行此脚本时,最多需要15秒才能停止轨道。我想在这里分享脚本,看看是否有一个明显的问题,或者是否有更简单,更有效的方法来处理它。

我感谢任何帮助!

tell application "System Events"
    if (name of processes) contains "iTunes" then
        set iTunesRunning to true
    else
        set iTunesRunning to false
    end if
    if (name of processes) contains "Rdio" then
        set RdioRunning to true
    else
        set RdioRunning to false
    end if
end tell

if RdioRunning then
    tell application "Rdio"
        if player state is paused or player state is stopped then
            play
        else if player state is playing then
            pause
        end if
    end tell
else if iTunesRunning then
    tell application "iTunes"
        if player state is paused or player state is stopped then
            play
        else if player state is playing then
            pause
        end if
    end tell
end if

1 个答案:

答案 0 :(得分:1)

很难找到这些问题。通常你的脚本看起来很好。这里有一些可能对您的问题有帮助的想法。

一般来说,在运行时解释applescripts,这意味着每次运行脚本时,字节码都必须由另一个程序(applescript runner)更改为机器语言代码......这通常不是问题但是在你的情况下,也许它会导致一些缓慢。所以我的想法是编写你的脚本,这样就不需要了。我们可以通过将脚本保存为applescript应用程序来实现,因为应用程序以机器语言形式保存,因此不需要其他程序来执行代码。此外,我们可以利用两个应用程序的命令是相同的,因此我们可以使用“使用术语”块。在您的代码中,您可以两次查询“进程名称”的系统事件,因此我们可以进行的最后一次优化只执行一次。

所以试试这个,看看它是否有帮助。我不确定它会但是值得一试。请记住将其另存为应用程序。

    tell application "System Events" to set pNames to name of application processes

    if "Rdio" is in pNames then
        set appName to "Rdio"
    else if "iTunes" is in pNames then
        set appName to "iTunes"
    else
        return
    end if

    using terms from application "iTunes"
        tell application appName
            if player state is paused or player state is stopped then
                play
            else if player state is playing then
                pause
            end if
        end tell
    end using terms from

编辑: 如果上述代码无效,请尝试此操作。如上所述,尝试将其作为应用程序,看看它是否有帮助。相同的原则适用于...少一个系统事件查询和保存为应用程序以防止需要解释代码。

tell application "System Events" to set pNames to name of application processes

if "Rdio" is in pNames then
    tell application "Rdio"
        if player state is paused or player state is stopped then
            play
        else if player state is playing then
            pause
        end if
    end tell
else if "iTunes" is in pNames then
    tell application "iTunes"
        if player state is paused or player state is stopped then
            play
        else if player state is playing then
            pause
        end if
    end tell
end if