How to convert Youtube to mp3 and download it super-safely [Python]

This time I will summarize how to download the videos posted on YouTube as mp3.

Reference sites and github are also posted.

If you have any mistakes or questions, please comment.

important point

I mainly download videos that I personally uploaded to YouTube and convert them to mp3.

Therefore, we are not responsible for any problems caused by using the sound source obtained from the video posted by someone other than yourself.

Many people say that private use is okay, but please do so at your own discretion. Please see below with that intention!

Finished product

It is just an example. Suppose you want to convert https://www.youtube.com/watch?v=E8bUKuF9v10 to mp3.

Where it opened

2020-09-10_22h16_22.png

2020-09-10_22h16_57.png

File generation

2020-09-10_22h17_19.png

2020-09-10_22h18_17.png

All dates can be aligned.

In other words, they are arranged in the order of download. 2020-09-10_22h18_36.png

By the way, if you press Quit at the first stage, the window will close, and even if you enter To Mp3, DeleteURL, Paste when nothing is entered, the operation will not occur.

environment

directory

...\ffmpeg~static\bin
Since there is a main file of ffmpeg in this, pass the path there. Also put the yououtue-dl exe file in the bin. That way, you can launch the exe anywhere in the command prompt.

    -bin
      - ffmpeg.exe
      - ffplay.exe
      - ffprobe.exe
      - youtube-dl.exe

The background I made and the structure I wanted to make

There are countless youtube video downloaders on the net, but I didn't want to get the data back from an unfamiliar site.

Therefore, I decided to complete it on my own PC.

At first, I didn't know anything about dedicated software, but as I googled, I found a good one, and I felt that this could be achieved.

The function to be implemented was very simple, so I made it possible to operate it with GUI.

Also, if it is a Python file, it can be converted to an exe immediately, so it can be distributed to friends.

Tkinter was famous as a GUI, but when I tried it, I felt nauseous, so I used pysimplegui.

Thanks to that, I think the GUI was completed in a short time.

code

github:

https://github.com/cota-eng/youtube-dl-in-windows

Code commentary

I will explain it separately.

Module library import

import subprocess
import PySimpleGUI as sg
import sys
import re
import os
import pyperclip
from win32_setctime import setctime
from datetime import datetime

First in the function

All are py simplegui programs. It is a flow to decide the color scheme, create the layout, and open the window.

The meaning of each button and text field is the same as that of English words.

sg.theme("SystemDefault")
    layout = [
        [sg.Text("Please Input Youtube URL!")],
        [sg.Button(
            'Quit', size=(34, 2))],
        [sg.Button('To Mp3', size=(34, 2))],
        [sg.InputText('', size=(39, 3))],
        [sg.Button('DeleteURL', size=(16, 2)),
         sg.Button('Paste', size=(16, 2))]
    ]
    window = sg.Window('From Youtube To mp3', layout)

while True

while True:
        event, values = window.read()
        url = values[0]

event=="Quit" It simply means that when this button is pressed, it exits the while loop.

if event == 'Quit':
            break

Instead of having a break at the bottom of the while loop, use if, elif, etc. to break at the appropriate scene.

Convert to mp3

event ==" "means the event that occurs when the button is clicked. You can uniquely specify the program by matching the name of the button. I will try to prevent bugs easily with the length of the url input during that event. Of the youtube links, the required length is about 40, so I safely set 32 as the standard.

len> 32 is True

elif event == 'To Mp3':
    if len(url) > 32:
        cmd = r'youtube-dl {} -x --audio-format mp3 -o "C:\Users\INPUTUSERNAME\Music\youtube-dl\%(title)s.%(ext)s"'.format(
            url)
        subprocess.call(
            cmd, cwd=r"C:\Program Files\ffmpeg-20200831-4a11a6f-win64-static\bin")

        res = subprocess.check_output(f'youtube-dl -e {url}'.split())
        res = res.decode('shift_jis').replace('\n', '')
        res += '.mp3'
        root = "C:\\Users\\INPUTUSERNAME\\Music\\youtube-dl\\"
        filename = root + res
        print(filename)
        date = datetime.now()
        year, month, day, hour, minute, second = date.year, date.month, date.day, date.hour, date.minute, date.second
        now = datetime(date.year, date.month, date.day,
                       date.hour, date.minute, date.second).timestamp()
        os.chdir(root)
        setctime(filename, now)
        os.utime(filename, (now, now))

I will explain it separately.


By using r "character string", all confusing symbols can be treated as characters. The raw string is raw. The command cmd was created from the readme of youtube-dl. youtube-dl % (title) s.% (Ext) s is the file name. It's a story on youtube-dl, so you should read it yourself for details. I got it by trial and error.

Call it with the subprocess call function. Also specify the directory with cwd.

cmd = r'youtube-dl {} -x --audio-format mp3 -o "C:\Users\INPUTUSERNAME\Music\youtube-dl\%(title)s.%(ext)s"'.format(
            url)
        subprocess.call(
            cmd, cwd=r"C:\Program Files\ffmpeg-20200831-4a11a6f-win64-static\bin")

Put the file name in res. This is also the result of trial and error, so please take a look and understand. After all, you can store all paths in filename by doing the following:

res = subprocess.check_output(f'youtube-dl -e {url}'.split())
                res = res.decode('shift_jis').replace('\n', '')
                res += '.mp3'
                root = "C:\\Users\\INPUTUSERNAME\\Music\\youtube-dl\\"
                filename = root + res
                print(filename)

Set the creation time etc. from the datetime library. Strictly speaking, other than the update date and time is set automatically when it is created, but for some reason the update date and time was not updated.

Therefore, I was able to realize it by embedding the datetime in my own way, referring to the following site.

Reference URL: https://srbrnote.work/archives/4054

By the way, if you use powershell,

Set-ItemProperty hogehoge.txt -name CreationTime -value $(Get-Date)

Set-ItemProperty hogehoge.txt -name LastWriteTime -value $(Get-Date)

It's easy to do, but I heard that powershell cannot be used with python, so I used the os module.

date = datetime.now()
year, month, day, hour, minute, second = date.year, date.month, date.day, date.hour, date.minute, date.second
now = datetime(date.year, date.month, date.day,
                date.hour, date.minute, date.second).timestamp()
os.chdir(root)
setctime(filename, now)
os.utime(filename, (now, now))

When len <= 32

Simply close the window once, and when you type and run the same as when you first opened it, it will be played.

else:
    window.close()
    layout = [
        [sg.Text("Please Input youtube URL!")],
        [sg.Button('Quit', size=(34, 2))],
        [sg.Button('To Mp3', size=(34, 2))],
        [sg.InputText('', size=(39, 3))],
        [sg.Button('DeleteURL', size=(16, 2)),
                     sg.Button('Paste', size=(16, 2))]
        ]
        window = sg.Window('From youtube To mp3', layout)

paste event

That's right, paste pastes the copied link. Button operation is easier, so I implemented it.

Since it is not possible to input to gui only with pyperclip, it was solved by closing the window, assigning the contents of pyperclip to a variable, and opening a window with that variable as the initial value.

elif event == 'Paste':
    window.close()
    paste_url = pyperclip.paste()
    layout = [
        [sg.Text("Please Input youtube URL!")],
        [sg.Button('Quit', size=(34, 2))],
        [sg.Button('To Mp3', size=(34, 2))],
        [sg.InputText(paste_url, size=(39, 3))],
        [sg.Button('DeleteURL', size=(16, 2)),
         sg.Button("Paste", size=(16, 2))]
    ]
    window = sg.Window('From youtube To mp3 ', layout)

delete event

This is the same idea as before. Instead of having it deleted, I closed the window and called a window that had no input.

elif event == 'DeleteURL':
            window.close()
            layout = [
                [sg.Text("Please Input youtube URL!")],
                [sg.Button('Quit', size=(34, 2))],
                [sg.Button('To Mp3', size=(34, 2))],
                [sg.InputText('', size=(39, 3))],
                [sg.Button('DeleteURL', size=(16, 2)),
                 sg.Button('Paste', size=(16, 2))]
            ]
            window = sg.Window('From youtube To mp3', layout)

that's all

I'm sorry that the code is dirty, but I hope it helps.

I couldn't find a site that introduces and explains this series of steps, so I uploaded it to Qiita.

Thank you very much.

Recommended Posts

How to convert Youtube to mp3 and download it super-safely [Python]
How to convert SVG to PDF and PNG [Python]
[Python] How to FFT mp3 data
Convert pixiv to mp4 and download from pixiv using python's pixivpy
Overview of Python virtual environment and how to create it
How to install OpenCV on Cloud9 and run it in Python
Convert the result of python optparse to dict and utilize it
How to package and distribute Python scripts
How to install and use pandas_datareader [Python]
[Python] How to convert a 2D list to a 1D list
How to convert Python to an exe file
python: How to use locals () and globals ()
[Python] How to calculate MAE and RMSE
How to use Python zip and enumerate
Easily download mp3 / mp4 with python and youtube-dl!
How to download youtube videos using pytube3
How to use is and == in Python
Read CSV file with Python and convert it to DataFrame as it is
Automatically search and download YouTube videos with Python
How to generate permutations in Python and C ++
[Python] How to read data from CIFAR-10 and CIFAR-100
[Python] How to use hash function and tuple.
How to install Cascade detector and how to use it
How to plot autocorrelation and partial autocorrelation in python
Python datetime How to calculate dates and convert strings strftime, strptime [Definitive Edition]
[Python] How to name table data and output it in csv (to_csv method)
How to install Python
How to install python
Convert timezoned date and time to Unixtime in Python2.7
How to convert / restore a string with [] in python
[Python] Convert decimal numbers to binary numbers, octal numbers, and hexadecimal numbers
[Python] [Django] How to use ChoiceField and how to add options
How to convert Python # type for Python super beginners: str
[Python] Convert general-purpose container and class to each other
Easy partial download of mp4 with python and youtube-dl!
[Python] How to specify the download location with youtube-dl
How to measure mp3 file playback time with python
How to convert floating point numbers to binary numbers in Python
How to convert JSON file to CSV file with Python Pandas
[Python] How to sort dict in list and instance in list
How to download files from Selenium in Python in Chrome
[Python] How to split and modularize files (simple, example)
[Python] How to create Correlation Matrix and Heat Map
How to use Decorator in Django and how to make it
python, php, ruby How to convert decimal numbers to n-ary numbers
Python # How to check type and type for super beginners
Try to make it using GUI and PyQt in Python
[2020.8 latest] How to install Python
[python] Convert date to string
How to install Python [Windows]
Convert numpy int64 to python int
python3: How to use bottle (2)
[Python] Convert list to Pandas [Pandas]
How to convert an array to a dictionary with Python [Application]
How to swap elements in an array in Python, and how to reverse an array.
[Python] How to use list 1
How to update Python Tkinter to 8.6
How to connect to various DBs from Python (PEP 249) and SQLAlchemy
[Pepper] How to utilize it?
[Introduction to Udemy Python 3 + Application] 36. How to use In and Not
How to use Python argparse