Can I pause YouTube in Chrome from the command line?

7,466

Solution 1

Well, I guess you could always use a tool like xdotool to send a k key-press to your YouTube window. The downside to this method is that you have to activate the window before sending the key-press (Chrome ignores keyboard input when it isn't focused).

The following script might work for you

#!/bin/bash

# Dependencies: xdotool (sudo apt-get install xdotool)

# Functions

save_active () {
    # get current workspace
    ActiveDesktop="$(xdotool get_desktop)"
    # get current active window ID
    ActiveWindowID="$(xdotool getactivewindow)"
    # get current active window name
    ActiveWindowName="$(xdotool getwindowname "$ActiveWindowID")"
}

restore_active(){
    xdotool set_desktop "$ActiveDesktop"
    # Activating the root window (Desktop) results in an error message, so we
    # try to avoid it
    [[ "$ActiveWindowName" != "Desktop" ]] && xdotool windowactivate "$ActiveWindowID"
}

youtube_playpause(){
  xdotool search --name YouTube windowactivate
  sleep 0.1
  xdotool key --clearmodifiers k
}

# Main

## save active window and desktop
save_active
## activate Chrome YouTube window and send keyboard event
youtube_playpause
## restore previously active window/desktop
restore_active

If controlling YouTube with your media keys is what you're after, there seem to be some extensions out there that claim to add this functionality to Chrome:

I haven't given them a try myself, yet.

Solution 2

Chromium now uses D-Bus to implement MPRIS for media content currently active in the browser, and browsers built on top of Chromium such as Google Chrome and Brave inherit this feature. That means media content currently active in such browsers can be controlled using a utility such as playerctl which can send and receive MPRIS commands.

You can download and install playerctl from their releases section on GitHub and then run this command to pause currently running media in Chrome:

$ playerctl pause

Or you can control a specific instance of Chrome:

$ playerctl --list-all
chrome.instance24818

$ playerctl --player=chrome.instance24818 pause

Solution 3

You could start the Chrome session (with your Youtube playlist) using the Chrome WebDriver:

WebDriver is an open source tool for automated testing of webapps across many browsers. It provides capabilities for navigating to web pages, user input, JavaScript execution, and more. ChromeDriver is a standalone server which implements WebDriver's wire protocol for Chromium. ChromeDriver is available for Chrome on Android and Chrome on Desktop (Mac, Linux, Windows and ChromeOS).

Install the following dependency:

sudo apt-get install python-selenium

And download the Chromedriver from here, select the one corresponding to your architecture e.g:

http://chromedriver.storage.googleapis.com/2.14/chromedriver_linux64.zip or http://chromedriver.storage.googleapis.com/2.14/chromedriver_linux32.zip

Extract the chromedriver file for example in your $HOME folder.

Then start the chromedriver from python, open a terminal and type:

$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> from selenium import webdriver
>>> from selenium.webdriver.chrome.options import Options
>>> chrome_options = Options()
>>> chrome_options.add_argument("--disable-sync")
>>> driver = webdriver.Chrome(os.path.expanduser('~/chromedriver'), chrome_options=chrome_options)
>>> # Open the desired youtube page:
>>> driver.get('https://www.youtube.com/watch?v=NxD_kWK8A5M&list=PLMquns5MbFKm_cVrB0ZjKlIlS5HCQL1dL')
>>> # Let selenium find the player container <div>
>>> video = driver.find_element_by_id("player-api")
>>> # And just click to play/pause your video:
>>> video.click()
>>> 

Note: You can still use the Chrome instance started by the Chrome WebDriver for browsing in other tabs. even if the Youtube tab is not the active one (no focus). The video.click() events will continue to work.

enter image description here

Solution 4

Easy: run the spotify/youtube in one session of chrome and all your other stuff in another chrome session. Then just

kill -SIGSTOP [pid]

to pause, and:

kill -SIGCONT [pid]

to resume.

If you make a little script to open two sessions of chrome, by:

google-chrome http://spotify.com/myplaylist http://youtube.com/myplaylist &
pgrep google-chrome > /tmp/TimChromepid.RUN
google-chrome &

and have the pid ready for your toggle script:

if [ -f /tmp/TimChromepid.RUN ]; then
  mv /tmp/TimChromepid.RUN /tmp/TimChromepid.PSD
  kill -SIGSTOP < /tmp/TimChromepid.PSD
else
  mv /tmp/TimChromepid.PSD /tmp/TimChromepid.RUN
  kill -SIGCONT < /tmp/TimChromepid.RUN
fi

It would pause spotify and Youtube and whatever you put in the first Chrome session.

Share:
7,466

Related videos on Youtube

Tim
Author by

Tim

My name is Tim. I've graduated from the University of Nottingham with a First Class Computer Science BSc with Hons. In my spare time I do computer programming, often C or JavaScript, but also shell scripts, and answering questions on Stack Exchange. I used to spend most of my time on Ask Ubuntu; now I mostly browse the HNQ or Meta Stack Exchange. If you want to contact me it's [email protected] Do you need a reliable VPS? Try Digital Ocean. Sign up with this link for $10 free. One of my favourite sites is Kiva.org, a micro-funding organisation that allows people to lend money via the Internet to low-income entrepreneurs and students in over 80 countries. Kiva's mission is “to connect people through lending to alleviate poverty.” With just $25 you can make a difference - and 99% of loans are paid back in full - so you can lend again and again!

Updated on September 18, 2022

Comments

  • Tim
    Tim almost 2 years

    I can pause Spotify by pausing all system programs playing (well, toggling). How can I do something like that to pause/play YouTube videos in Google Chrome?

    • MGodby
      MGodby over 9 years
      These should probably be separate questions, as it may require 2 different answers from two different people to answer this. Good questions, though.
    • Thomas Ward
      Thomas Ward over 9 years
      This would require some kind of API call to the HTML5 or Flash video player through Chrome - I don't think there's any kind of setup that exists that can do that.
    • Tim
      Tim over 9 years
      @Thom I wondered if there was an API that could... Like an offline version of ifttt.
    • Thomas Ward
      Thomas Ward over 9 years
      @Tim it'd still be a Chrome thing - if you want to control it in Chrome then Chrome and the Flash plugin would need to have an API that listens locally, and running a youtube and chrome window shows no kind of API starting up. You'd probably need an offline YouTube client with an API to do that, but it probably won't have Chrome intergration...
    • Tim
      Tim over 9 years
      @Thomas Is there a local YouTube client for linux atm?
    • Thomas Ward
      Thomas Ward over 9 years
      @Tim I do not know - that may be a different question you would post.
    • Kaz Wolfe
      Kaz Wolfe over 9 years
      The only thing I can think of is something like a Greasemonkey script. if (/path/to/a/temp/file) = pauseVideo then click("Pause");
    • Aiphee
      Aiphee over 9 years
      Ubuntu webapp should be able to do that, im not sure if it works now. Here is video: youtube.com/watch?v=8CtKNf53HvA
    • Glutanimate
      Glutanimate over 9 years
      @Tim As far as a dedicated YouTube player is concerned: There's Minitube, for one. VLC and MPV/Smplayer also support YouTube playback. A lot of options out there.
  • Fabby
    Fabby over 9 years
    And knowing the Tim from the answers instead of the questions, he's now [facepalm]ing himself! ;-) It's a bit of a rough draft now, but you'll get the gist... If not, I'll edit and clean up a bit... (drop me a note @Fabby)
  • Sergiy Kolodyazhnyy
    Sergiy Kolodyazhnyy over 9 years
    I know Firefox has plugin container, so we could pause that with the SIGSTOP and Internet should still be accessible , but what about chrome ?
  • Fabby
    Fabby over 9 years
    @Serg: the above "pauses" one entire chrome session with everything in it, so that's why you need two: One to continue surfing while the other one is paused... (or not, depending on the use case) ;-)
  • Tim
    Tim over 9 years
    How do I get it to auto get the PID? does it do that?
  • Fabby
    Fabby over 9 years
    @Tim Chat? AskUbuntu General Room?
  • Tim
    Tim over 9 years
    @Fabby at school atm - later or tomorrow? What time are you online?
  • Fabby
    Fabby over 9 years
    I'm in GMT+3. Just leave another @Fabby when you get back home...
  • Tim
    Tim over 9 years
    Ooh, very nice! What about being signed into chrome?
  • Tim
    Tim over 9 years
    It says that sync is disabled by my admin...
  • Sylvain Pineau
    Sylvain Pineau over 9 years
    @Time I've updated my answer with a possible workaround for the sync error. I can't test it myself as it works out of the box. Could you please give it a try?
  • Fabby
    Fabby over 9 years
    Wow! If we can get that to work on Tim's machine, that would mean everything could be scripted from python...
  • Tim
    Tim over 9 years
    Nope, still says it is disabled... :/
  • Sylvain Pineau
    Sylvain Pineau over 9 years
    @Tim Let's try with --incognito, I've updated (again) my answer to add this option
  • Sylvain Pineau
    Sylvain Pineau over 9 years
    @Tim, I'd like to continue working on your question. would it be possible to get a screenshot of both the terminal and the launched chrome session? what could be interesting to know is the list of your extensions. One of them may be the sync blocker. I did my tests on a fresh install with only one account signed in but did not install any extensions on top of it. Thanks.
  • Sylvain Pineau
    Sylvain Pineau over 9 years
    @Tim Now that you know how to add arguments, may be you could try the following ones: chrome_options.add_argument("--disable-extensions") and/or chrome_options.add_argument("--bwsi")
  • Tim
    Tim over 9 years
    When I launch it, I'm not logged in. I will try in a VB, and screenshot when I get home (1 hour).
  • Tim
    Tim over 9 years
    These aren't working for me I'm afraid. However, thanks for the suggestion. The other issue I would have it spotify is paused by the button, and I don't want to be "switching" them... +1 anyway though for the idea.
  • Tim
    Tim over 9 years
    Atually, the first one does work. However, that is now monopolising the Media Keys... :/ I think I'd like an extention like it that doesn't use media keys. I will see if I can extract and reprogram that one. I'm gonna offer another +50 bounty and give you that one.
  • Tim
    Tim over 9 years
    I'm not going to accept this answer, simply because it doesn't integrate as nicely... I also would like to be able to use the same window for browsing. Thanks for your help though @Fabby.
  • Fabby
    Fabby over 9 years
    And thanks for the feed-back! Sylvain's solution looks much more elegant anyway, so if you need any help with that, drop by in the chat room! ;-)
  • Tim
    Tim over 9 years
    Changed my mind, I'll put up with no spotify play / pause with media keys. +100
  • Glutanimate
    Glutanimate over 9 years
    @Tim Thanks for assigning me the bounty. That's very generous of you. FWIW, to still be able to control Spotify via the keyboard you could use the DBUS interface. For instance, dbus-send --print-reply --session --dest=org.mpris.MediaPlayer2.spotify /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player.PlayPause will play/pause a track. I don't know if Unity supports this, but you could try assigning these DBUS commands to CTRL + <respective media key>.
  • Nikana Reklawyks
    Nikana Reklawyks over 4 years
    Problems with this script : it gets confused when there are several "youtube" windows. In particular, this very window (this question) has Youtube in its name so counts as one. When there are several, it seems to cycle through them as you call it again and again. That's a great deal of awesome pointers all the same, thanks much.
  • Nikana Reklawyks
    Nikana Reklawyks over 4 years
    I changed Youtube in the search --name part to "Youtube - Google Chrome" and closed my other youtube windows and it's getting better. Another issue arises if you have several youtube tabs in a window, but the active tab is not the one playing, then this script will toggle the active tab (-> two things are playing now) rather than the audio-playing tab. Though I guess those concerns are beyond the scope of this question.
  • Alexander Shukaev
    Alexander Shukaev about 3 years
    To the top please!
  • Jeff_V
    Jeff_V over 2 years
    I second this motion.