A Python Script to Play YouTube Videos in VLC by Just Copying the Link

A Python Script to Play YouTube Videos in VLC by Just Copying the Link

Automate playing YouTube videos in VLC with Python

Photo by [cottonbro](https://cdn.hashnode.com/res/hashnode/image/upload/v1626495098029/tjC6wK2eA.html) from [Pexels](https://www.pexels.com/photo/browsing-youtube-5077064/?utm_content=attributionCopyText&utm_medium=referral&utm_source=pexels)Photo by cottonbro from Pexels

In my previous post, I mentioned that I’ve coded a script that plays YouTube videos in VLC just by copying the video link. You can find the post here.

Today, we will be coding the script together from scratch. You can find the full code at the end of this post.

If you don’t have any intentions of Installing Python or Going through the code, you can find both the exe file and source code on the Github repo, here. Just run the .exe file and you are good to go.

Prerequisites: Python installed on your computer and basic knowledge of Python (just knowing the syntax of functions and how to import libraries would be more than enough, I’ll take care of the rest).

I’ve explained each and every line, so bear with me till the end.

NOTE: Remember that Python is based on indentation. So don’t mess up the indentation while writing the code.

As the post was becoming longer than expected, I explained some of the code with comments in the code. But, if you have any doubts, you can ask them in the comments section OR ping me at , I’ll get back to you for sure. You can also find me on Twitter.

So, let’s get started!

Step 1: Import all the required libraries

import clipboard  // To access the link you copied.
import threading  

import time 
// To delay the execution of the function for a given time period

import os      // To access the command line and execute commands.
import sys     // To close the exe file.

from pathlib import Path 
// To get directory path of the source code file

from infi.systray import SysTrayIcon
// To include the exe in the System Tray of Icons

from win10toast import ToastNotifier  
// To show a Notification that exe is working.

from win32gui import GetForegroundWindow, GetWindowText
// To get the current window and that window’s text

The other libraries are used for :

Threading → To allow spawning multi-threads in the program (We need not use threading in this code but I included it just in case if I use it. You can remove it or comment it if required)

Time → To delay the execution of the function for a given time period (You can omit this too)

For System Tray → Click the arrow button beside your Wifi or Battery icon

Step 2: Setup the Notification

toaster = ToastNotifier()

toaster.show_toast("YLC","I am running in Background ✔️",icon_path=str(Path(__file__).parent.absolute())+"\\icon\\vlc_yt.ico",duration=3,threaded=True)

show_toast Parameters :

Name to show up in notification : “YLC”

Any message you want to show : “I am running in Background ✔️”

Path of Icon to be used in the notification: str(Path(file).parent.absolute())+”\icon\vlc_yt.ico”

Path(file).parent.absolute() → It represents the path of the parent directiory of the source code file and str() converts it into a string.

”\icon\vlc_yt.ico” → add the rest of the path of the icon relative to the source code file.

Duration : How long the notification should show up?

Threaded : Whether it is threaded or not ( We are using it as a thread here, so set to True)

Step 3: Provide menu options and include Systray icon

menu_options = (("About", None, about),)

systray = SysTrayIcon(str(Path(__file__).parent.absolute())+"\\icon\\vlc_yt.ico", "YT_VLC", menu_options,on_quit=done)

systray.start() // Initializing the SysTrayIcon

menu_options : For context menu options of systray icon. Here, we made only one option. You can have more if required (about is the function that we will create later) We can access the options by Right-Clicking the icon in system tray.

SysTrayIcon Parameters :

First parameter : Path to the icon to show in the systray (Path can be set as explained above for the toaster icon).

Second parameter : The hover text to show when the mouse hovers over the systray icon. The Traybar runs in its own thread, so the user script can continue to run.

Third parameter : menu_options that we prepared.

Fourth parameter : “on_quit” → The menu has default quit option, which when clicked, executes the function stored in this “on_quit” parameter. Here,the assigned function is “done” (we will be creating it later in the post)

(If the icons are either not found or not available for some reason, it uses a default script icon)

Step 4: Threading

t1 = threading.Thread(target=get_active)
t1.start() // Initializing the thread

We create only one thread here (hence I mentioned that you can omit it). I’ll also provide the link to code with no threading later in the post.

t1 = threading.Thread(target=some_function) → a function is assigned to target, which runs as a single thread ( Here, get_active is the function, we will create it later ).

Step 5 : We create the required functions

To stop the exe file from running : (the “on_quit” parameter in SysTrayIcon uses this function)

def done(systray): 
  sys.exit() systray is the variable in which we stored the SysTrayIcon.

“systray” is the variable in which we stored the SysTrayIcon. It is passed as an argument to let the code know that “done” belongs to this “SysTrayIcon”

For the “about” function that we provided in menu_options:

def about(systray): //systray is passed for the same reason as above

    command_about="start https://{any_link}"

    os.system(command_about) 
    // Redirects you to the above mentioned link when clicked on "About" in menu

For “get_active” provided in threading:

def get_active():

    while True: 
    // "True" makes sure that the code keeps on running unless the code is stopped. So, the code keeps an eye on clipboard for copy actions unless it is stopped.

        time.sleep(0.5)
    // To delay the looping (to prevent cases like crash of program)

        window = GetWindowText(GetForegroundWindow())
        // saving the Window's name in window varable

        if(window[-6:]=="Chrome" or window[-4:]=="Edge"):
        // Checking if the window is either "Chrome"(last 6 characters of string) OR "Edge"(last 4 characters of string)

            run_step2()
            // if it is a valid window, then we call an extra function

The extra function that we call, if the window is valid (Chrome or Edge):

def run_step2():

    link=clipboard.paste() 
    // Recent Link in the clipboard is stored in variable link 

    if( ( link.find("https://www.youtube.com/watch?v=")==0 or link.find("https://www.youtube.com/playlist?list=")==0 ) and "-vlc" in link): 

    // Checking if the link is a valid youtube link (video or a playlist) and has "-vlc" in it. Scroll down for more explanation.

        link=link[:-4] 
        // Removing the "-vlc" part from link (last four characters)

        command = ("vlc " + link )
        // Adding vlc to link and saving in variable command
        // the space beside vlc is necessary or command execution

        os.system('cd /d C:\\Program Files\\VideoLAN\\VLC') 
        // Executing the above command in the cmd. The above path is the path to the VLC app installed in the desktop, not our YT_VLC.exe file. So,now we are in the VLC directory 

    os.system(command) 
    // here command = vlc <link of copied youtube video>
    // The command executes -> It opens VLC and plays the video

    clipboard.copy('')
    // This code makes sure that Clipboard sets back to "", an empty string. If not, then the VLC will open again and again when we close the VLC, because the video link remains as the recent link in the clipboard. So it needs to be set to some other invalid string (we use "" here)

else: 
// If it is not a youtube video or it does not have the "-vlc" in it

    pass // does nothing just passes out of this condition

The link.find(“required_string” == 0) checks if the position of “required_string” is 0th position i.e., at the start of the link. If it is at the start, then :

(“-vlc” in link ) checks for “-vlc” in the string (at any position). So, you must add “-vlc” at the end, so that when last 4 characters are removed, the link becomes valid to play in VLC.

Step 6: Sit back and watch that video play in your VLC with a click

Of course, you have to run the script before you copy the link.

If you do not have any intention of installing Python or going through this code, you can download the source code and the .exe file that I have provided here. Just run the .exe file and you are good to go.

Thanks for bearing with me till the end. I know it’s a long post, but I hope you learned something new today. Please share your thoughts in the comment section.

The code without threading can be found here.

You can run any of the codes in your code editor and it should work like a charm. Make sure you have Python installed before executing this code.

The FULL code:

import clipboard
import threading 
import time
import os
import sys
from pathlib import Path
from infi.systray import SysTrayIcon
from win10toast import ToastNotifier
from win32gui import GetWindowText, GetForegroundWindow

def done(systray):

    sys.exit()


def about(systray):

    command_about="start https://github.com/mohithgupta/Auto-YT_VLC-player"

    os.system(command_about)


def run_step2():

    link=clipboard.paste()

    if( ( link.find("https://www.youtube.com/watch?v=")==0 or link.find("https://www.youtube.com/playlist?list=")==0 ) and "-vlc" in link):
        link=link[:-4]
        command = ("vlc " + link)  
        os.system('cd /d C:\\Program Files\\VideoLAN\\VLC')
        os.system(command)
        clipboard.copy('')

    else:
        pass

def get_active():

    while True:

        time.sleep(0.5)

        if(GetWindowText(GetForegroundWindow())[-6:]=="Chrome" or GetWindowText(GetForegroundWindow())[-4:]=="Edge"):
            run_step2()


if __name__ == "__main__": 

    toaster = ToastNotifier()
    toaster.show_toast("YLC","I am running in Background ✔️",icon_path=str(Path(__file__).parent.absolute())+"\\icon\\vlc_yt.ico",duration=3,threaded=True)
    menu_options = (("About", None, about),)
    systray = SysTrayIcon(str(Path(__file__).parent.absolute())+"\\icon\\vlc_yt.ico", "YT_VLC", menu_options,on_quit=done)
    systray.start()
    t1 = threading.Thread(target=get_active) 
    t1.start()