如何通过键盘快捷键或菜单栏暂停YouTube视频?


17

是否有一款软件可以通过键盘快捷键或方便访问的按钮(例如,可以通过位于屏幕右上方的菜单栏中)?必要的点击次数越少越好。

这里的关键是我希望能够在任何应用程序中暂停视频,也就是说,当Google Chrome 不是最重要的应用程序时(例如,TextEdit或Microsoft Word是最重要的应用程序)。

iOS内置了此快捷方式。如果从屏幕底部向顶部轻扫,则会出现媒体控件。这些控件可以操纵源自Safari标签的所有音频。

我的网络浏览器是Google Chrome。

OS X El Capitan,版本10.11.6。


我也愿意使用AppleScript(可以在FastScripts.app中将其分配给按键组合)来完成此任务。但是,我无法想象通过AppleScript可以完成如此​​复杂的任务。


1
因此,您在寻找菜单栏解决方案,而不仅仅是点击空格键?还是用鼠标单击“播放/暂停”按钮?
Monomeeth

1
@Monomeeth请参阅我的编辑。我忘了提到Chrome不是活动的应用程序。视频在后台播放。因此,要暂停视频,我必须单击Chrome窗口,单击包含视频的选项卡,然后才可以使用空格键或单击鼠标左键来暂停视频。
魔球的范围

1
您正在寻找类似我是否理解过的问题: beardedspice.github.io
enzo

@enzo我已经下载了BeardedSpice,这正是我想要的。BeardedSpice非常适合我的需求。如果您想将其发布为答案,我会很乐意接受。谢谢!
rubik球体

我真的想知道为什么Google不能使YouTube的键盘“播放/暂停”按钮(F8)起作用,因为当您在Chrome中访问Google Play音乐时,它确实可以正常工作。
calum_b

Answers:


19

********** 更新的解决方案 **********

此更新是对OP原始问题的直接解决方案。

下面的AppleScript代码将添加“播放/暂停YouTube”状态菜单项,其中包含在浏览器是否可见的情况下在Google Chrome或Safari中播放或暂停任何YouTube视频的选项。将下面的AppleScript代码保存为Script Editor.app中的“保持打开”应用程序。

use framework "Foundation"
use framework "AppKit"
use scripting additions

property StatusItem : missing value
property selectedMenu : ""
property defaults : class "NSUserDefaults"
property internalMenuItem : class "NSMenuItem"
property externalMenuItem : class "NSMenuItem"
property newMenu : class "NSMenu"

my makeStatusBar()
my makeMenus()

on makeStatusBar()
    set bar to current application's NSStatusBar's systemStatusBar
    set StatusItem to bar's statusItemWithLength:-1.0
    -- set up the initial NSStatusBars title
    StatusItem's setTitle:"Play/Pause YouTube"
    -- set up the initial NSMenu of the statusbar
    set newMenu to current application's NSMenu's alloc()'s initWithTitle:"Custom"
    newMenu's setDelegate:me (*
    Requied delegation for when the Status bar Menu is clicked  the menu will use the delegates method (menuNeedsUpdate:(menu)) to run dynamically update.*)
    StatusItem's setMenu:newMenu
end makeStatusBar

on makeMenus()
    newMenu's removeAllItems() -- remove existing menu items
    set someListInstances to {"Play/Pause YouTube - Safari", "Play/Pause YouTube - Chrome", "Quit"}
    repeat with i from 1 to number of items in someListInstances
        set this_item to item i of someListInstances
        set thisMenuItem to (current application's NSMenuItem's alloc()'s initWithTitle:this_item action:("someAction" & (i as text) & ":") keyEquivalent:"")
        (newMenu's addItem:thisMenuItem)
        (thisMenuItem's setTarget:me) -- required for enabling the menu item
    end repeat
end makeMenus

on someAction1:sender
    clickClassName2("ytp-play-button ytp-button", 0)
end someAction1:

on someAction2:sender
    clickClassName("ytp-play-button ytp-button", 0)
end someAction2:

on someAction3:sender
    quit me
end someAction3:

to clickClassName2(theClassName, elementnum)
    if application "Safari" is running then
        try
            tell application "Safari"
                tell window 1 to set current tab to tab 1 whose URL contains "youtube"
                do JavaScript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();" in document 1
            end tell
        end try
    end if
end clickClassName2

to clickClassName(theClassName, elementnum)
    tell application "Google Chrome" to (tabs of window 1 whose URL contains "youtube")
    set youtubeTabs to item 1 of the result
    tell application "Google Chrome"
        execute youtubeTabs javascript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();"
    end tell
end clickClassName

在此处输入图片说明

如果您希望新的...播放暂停YouTube状态Menu.app仅在状态菜单中而不在Dock中可见,则可以在Finder中右键单击该应用,然后选择“显示包内容”选项。在目录文件夹中,在任何文本编辑器中打开Info.plist文件,并添加以下两行。然后保存并关闭该文件。

<key>LSBackgroundOnly</key>
<true/>

如果您不满意直接编辑.plist文件,则下面的AppleScript代码将允许您选择要在Dock运行时隐藏的应用程序。

如果已将选定的应用程序设置为从Dock隐藏,则您将获得的唯一选择是取消隐藏该应用程序,使其在Dock运行时不可见……反之亦然。

该脚本特别适用于隐藏的“保持打开的应用程序”,其中闲置处理程序的应用程序图标在运行时不会出现在Dock中。

property fileTypes : {"com.apple.application-bundle"}
property plistFileItem : "  <key>LSBackgroundOnly</key>" & linefeed & " <true/>"

activate
set chosenApp to (choose application with prompt ¬
    "Choose  The Application You Want Hidden From The Dock While It Is Running" as alias)

tell application "System Events" to set appName to name of chosenApp
set plistFile to ((POSIX path of chosenApp) & "/Contents/info.plist") as string
set plistFileContents to (read plistFile)
set plistFileItemExists to plistFileItem is in plistFileContents

if plistFileItemExists then
    activate
    set theChoice to button returned of (display dialog ¬
        "Would you like to un-hide " & quote & appName & quote & ¬
        " from the Dock while it's running?" buttons {"Cancel", "Un-Hide"} ¬
        default button 2 cancel button 1 with title "Make A Choice")
else
    activate
    set theChoice to button returned of (display dialog ¬
        "Would you like to hide " & quote & appName & quote & ¬
        " from the Dock while it's running?" buttons {"Cancel", "Hide"} ¬
        default button 2 cancel button 1 with title "Make A Choice")
end if

if theChoice is "Hide" then
    tell application "System Events" to tell contents of property list file plistFile ¬
        to make new property list item at end with properties ¬
        {kind:string, name:"LSBackgroundOnly", value:true}
else if theChoice is "Un-Hide" then
    tell application "System Events" to tell contents of property list file plistFile ¬
        to make new property list item at end with properties ¬
        {kind:string, name:"LSBackgroundOnly", value:false}
else
    return
end if


************ 原始解决方案 ************

无论是否显示Google Chrome,此脚本都会在YouTube上的YouTube视频中单击视频上的播放/暂停按钮。

to clickClassName(theClassName, elementnum)
    tell application "Google Chrome" to (tabs of window 1 whose URL contains "youtube")
    set youtubeTabs to item 1 of the result
    tell application "Google Chrome"
        execute youtubeTabs javascript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();"
    end tell
end clickClassName    

clickClassName("ytp-play-button ytp-button", 0)

这是用于Safari的脚本版本

to clickClassName2(theClassName, elementnum)
    tell application "Safari"
        tell window 1 to set current tab to tab 1 whose URL contains "youtube"
        do JavaScript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();" in document 1
    end tell
end clickClassName2

clickClassName2("ytp-play-button ytp-button", 0)

为了使OP拥有完整的AppleScript解决方案,我将原始答案又向前了一步。

更新

我终于弄明白了。我用Xcode创建了一个AppleScript应用程序。最初,我的项目仅从一个按钮窗口开始,以控制当前在Chrome或Safari中处于活动状态的YouTube视频。这个项目已经成长为包含多个实用程序的应用程序。此GIF显示了YouTube暂停按钮,可在Chrome和Safari中控制YouTube。我将按钮操作链接到我最初在脚本编辑器中编写的AppleScript。

在此处输入图片说明

这是在AppDelegate.applescript文件中工作的Xcode应用程序的快照。

在此处输入图片说明

这是我创建的使程序正常运行的文件中的代码。

script AppDelegate

    property parent : class "NSObject"


    -- IBOutlets
    property theWindow : missing value

    to clickClassName(theClassName, elementnum) -- Handler for pausing YouTube in Chrome
        if application "Google Chrome" is running then
            try
                tell application "Google Chrome" to (tabs of window 1 whose URL contains "youtube")
                set youtubeTabs to item 1 of the result
                tell application "Google Chrome"
                    execute youtubeTabs javascript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();"
                end tell
            end try
        end if
    end clickClassName

    to clickClassName2(theClassName, elementnum) -- Handler for pausing YouTube in Safari
        if application "Safari" is running then
            try
                tell application "Safari"
                    tell window 1 to set current tab to tab 1 whose URL contains "youtube"
                    do JavaScript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();" in document 1
                end tell
            end try
        end if
    end clickClassName2

    on doSomething:sender -- Calls the Chrome YouTube Handler
        clickClassName("ytp-play-button ytp-button", 0)
    end doSomething:

    on doSomething14:sender -- Calls the Safari YouTube Handler
        clickClassName2("ytp-play-button ytp-button", 0)
    end doSomething14:

    on doSomething2:sender -- Hide and or show the Menu Bar
        tell application "System Preferences"
            reveal pane id "com.apple.preference.general"
        end tell
        tell application "System Events" to tell process "System Preferences" to tell window "General"
            click checkbox "Automatically hide and show the menu bar"
        end tell
        delay 1
        quit application "System Preferences"
    end doSomething2:

    on doSomething3:sender -- Sets Display resolution to the second lowest setting (15 inch Built In Retina Display - MBP)
        tell application "System Preferences"
            reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
        end tell
        tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
            click radio button "Scaled" of radio group 1 of tab group 1
            click radio button 2 of radio group 1 of group 1 of tab group 1
        end tell
        quit application "System Preferences"
    end doSomething3:

    on doSomething4:sender -- Sets Display resolution to the second highest setting (15 inch Built In Retina Display - MBP)
        tell application "System Preferences"
            reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
        end tell
        tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
            click radio button "Scaled" of radio group 1 of tab group 1
            click radio button 4 of radio group 1 of group 1 of tab group 1
        end tell
        quit application "System Preferences"
    end doSomething4:

    on doSomething5:sender -- Sets Display resolution to the highest setting (15 inch Built In Retina Display - MBP)
        tell application "System Preferences"
            reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
        end tell
        tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
            click radio button "Scaled" of radio group 1 of tab group 1
            click radio button 5 of radio group 1 of group 1 of tab group 1
        end tell
        quit application "System Preferences"
    end doSomething5:

    on doSomething6:sender -- Sets Display resolution to the lowest setting (15 inch Built In Retina Display - MBP)
        tell application "System Preferences"
            reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
        end tell
        tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
            click radio button "Scaled" of radio group 1 of tab group 1
            click radio button 1 of radio group 1 of group 1 of tab group 1
            delay 0.1
            click button "OK" of sheet 1
            quit application "System Preferences"
        end tell
    end doSomething6:

    on doSomething7:sender -- Displays a dialog with your current IP
        tell current application to display dialog (do shell script "curl ifconfig.io") with icon 2 buttons "OK" default button 1 with title "Your Current IP Address Is.." giving up after 5
    end doSomething7:

    on doSomething8:sender -- Shows hidden files in Finder
        do shell script "defaults write com.apple.finder AppleShowAllFiles TRUE\nkillall Finder"
    end doSomething8:

    on doSomething9:sender -- Hides hidden files in Finder if they are showing
        do shell script "defaults write com.apple.finder AppleShowAllFiles FALSE\nkillall Finder"
    end doSomething9:

    on doSomething10:sender  -- Brightness Highest
        tell application "System Preferences"
            reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
        end tell
        tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
        set value of value indicator 1 of slider 1 of group 2 of tab group 1 to 12
        end tell
        quit application "System Preferences"
    end doSomething10:

    on doSomething11:sender -- Brightness Lowest
        tell application "System Preferences"
            reveal anchor "displaysDisplayTab" of pane "com.apple.preference.displays"
        end tell
        tell application "System Events" to tell process "System Preferences" to tell window "Built-in Retina Display"
        set value of value indicator 1 of slider 1 of group 2 of tab group 1 to 0.1
        end tell
        quit application "System Preferences"
    end doSomething11:

    on doSomething12:sender -- Zoom
        tell application "System Events"
            key code 28 using {command down, option down}
        end tell
    end doSomething12:

    on doSomething13:sender -- Dictation On/Off
        tell application "System Events"
            keystroke "x" using {option down}
        end tell
    end doSomething13:

    on doSomething15:sender -- Enables Screensaver as Desktop background
        tell application "System Events"
            do shell script "/System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine -background"
        end tell
    end doSomething15:

    on doSomething16:sender -- Kills Screensaver Desktop background
        try
            tell application id "com.apple.ScreenSaver.Engine" to quit
        end try
    end doSomething16:


    on applicationWillFinishLaunching:aNotification
        -- Insert code here to initialize your application before any files are opened

    end applicationWillFinishLaunching:

    on applicationShouldTerminate:sender
        -- Insert code here to do any housekeeping before your application quits


        return current application's NSTerminateNow
    end applicationShouldTerminate:

    on applicationShouldTerminateAfterLastWindowClosed:sender -- Quits app when clicking red x

        return TRUE

    end applicationShouldTerminateAfterLastWindowClosed:

end script

我更新了代码,以便在单击Xco​​de中创建的YouTube暂停按钮时,无需将Chrome中的YouTube标签设为可见或活动标签

这是下载整个Xcode项目的链接

在此处输入图片说明

警告:桌面屏幕保护程序功能将冻结该应用程序。强制退出并重新打开后,退出活动屏幕保护程序的桌面屏幕保护程序功能将起作用。

事后思考: 我可能应该将每个AppleScript代码包装在“ try”语句中,以避免那些与此项目和系统类型不同的人遇到各种错误消息。(MacBook Pro 15英寸操作系统Sierra 10.12.6)

要使缩放功能起作用,必须在系统偏好设置中将其启用。

在此处输入图片说明

为了正确切换“听写开/关”,在系统首选项中启用听写命令的快捷方式必须与脚本中使用的快捷方式匹配

在此处输入图片说明

on doSomething13:sender -- Dictation On/Off
    tell application "System Events"
        keystroke "x" using {option down}
    end tell
end doSomething13:

目前,我正在研究仅在运行窗口的应用程序或菜单栏之间切换的功能


撇开display dialing ...您只需要这一行代码tell application "Google Chrome" to execute front window's active tab javascript "document.getElementsByClassName('ytp-play-button ytp-button')['0'].click();"。由于OP希望“暂停(和取消暂停)当前正在播放的YouTube视频”,因此Google已经打开,可以通过激活标签页将其最小化,并且上述一行代码将对其起作用。因此,无需激活窗口或代码中的内容,使用launch文档中所述的内容,在下
一条

3
这是一个非常聪明的解决方案!我决定使用第三方程序BeardedSpice(如enzo先前在评论中建议的那样),因为即使将包含视频的Chrome窗口最小化,并且BeardedSpice仍保持最小化,BeardedSpice仍然可以工作。BeardedSpice还可以与许多在线媒体播放器(不仅是YouTube)一起使用。但是,我很惊讶您发现如何在AppleScript中执行此操作。
魔球的范围

1
如果您将Xcode项目文件压缩存档并提供存档的下载链接,那将是非常好的。:)
user3439894

1
我只是整理一下代码,我将很快
回答

1
感谢您共享项目文件。如果我能再次投票赞成你的答案,我会的。:)
user3439894

1

以下是使用纯AppleScript进入菜单栏的方法。另存为应用stay open after run handler

附言:我从@ wch1zpink窃取了实际播放/暂停功能的代码,因此请同时投票给他们答案

--AppleScript: menu bar script -- Created 2017-03-03 by Takaaki Naganoya adapted by Josh Brown
--2017 Piyomaru Software
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"
--http://piyocast.com/as/archives/4502

property aStatusItem : missing value

on run
    init() of me
end run

on init()
    set aList to {"Google Chrome", "⏯", "", "Safari", "⏯​", "", "Quit"}
    set aStatusItem to current application's NSStatusBar's systemStatusBar()'s statusItemWithLength:(current application's NSVariableStatusItemLength)

    aStatusItem's setTitle:"🎛"
    aStatusItem's setHighlightMode:true
    aStatusItem's setMenu:(createMenu(aList) of me)
end init

on createMenu(aList)
    set aMenu to current application's NSMenu's alloc()'s init()
    set aCount to 1
    repeat with i in aList
        set j to contents of i
        if j is not equal to "" then
            set aMenuItem to (current application's NSMenuItem's alloc()'s initWithTitle:j action:"actionHandler:" keyEquivalent:"")
        else
            set aMenuItem to (current application's NSMenuItem's separatorItem())
        end if
        (aMenuItem's setTarget:me)
        (aMenuItem's setTag:aCount)
        (aMenu's addItem:aMenuItem)
        if j is not equal to "" then
            set aCount to aCount + 1
        end if
    end repeat

    return aMenu
end createMenu

on actionHandler:sender
    set aTag to tag of sender as integer
    set aTitle to title of sender as string

    if aTitle is "Quit" then
        current application's NSStatusBar's systemStatusBar()'s removeStatusItem:aStatusItem
    end if
    #Chrome
    if aTitle is "⏯" then
        clickClassName("ytp-play-button ytp-button", 0)
    end if
    #Safari
    if aTitle is "⏯​" then
        clickClassName2("ytp-play-button ytp-button", 0)
    end if
end actionHandler:

to clickClassName(theClassName, elementnum)
    tell application "Google Chrome" to (tabs of window 1 whose URL contains "youtube")
    set youtubeTabs to item 1 of the result
    tell application "Google Chrome"
        execute youtubeTabs javascript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();"
    end tell
end clickClassName

to clickClassName2(theClassName, elementnum)
    tell application "Safari"
        tell window 1 to set current tab to tab 1 whose URL contains "youtube"
        do JavaScript "document.getElementsByClassName('" & theClassName & "')[" & elementnum & "].click();" in document 1
    end tell
end clickClassName2

1
我看到两个问题,第一个是如果您从菜单栏退出,则AppleScript Application Dock Tile仍然存在,然后必须分别退出该应用程序。你可以添加一个quit 命令if aTitle is "Quit" then current application's ...的行代码来解决这个问题。第二个问题是,当选择使用深色菜单栏和Dock常规系统首选项时,您正在使用的符号显示不佳。除非将鼠标悬停在符号上,否则您实际上看不到它们。您可以考虑将带有符号的文本添加到菜单项。例如:Play/Pause YouTube ⏯​
user3439894 '18

感谢您提供有关暗模式的建议,该模式将进行调整。我将解决退出问题。
JBis

1
另外,在创建诸如此类的菜单附加应用程序时,我想隐藏LSUIElement = 1添加到name.app/Contents/Info.plist文件中的应用程序的Dock Tile 。IMO此类菜单附加应用程序无需显示应用程序的Dock Tile。
user3439894 '18

@ user3439894知道我还有更多应用程序,只是忘了添加即可随意编辑
。– JBis

还要注意,代码中的--http://piyocast.com/as/archives/4502注释不再有效,但是此答案Applescript是从菜单栏运行的吗?由原始代码作者撰写,包含曾经在该URL上使用的原始代码。答案还包括隐藏Dock Tile 的命令,例如:defaults defaults write /Applications/name_of_app.app/Contents/Info.plist LSUIElement -bool yes
user3439894 '18
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.