Іноді буває потрібно закачати якесь аудіо з ютуб, і воно або надто довге щоб користуватись якимось стороннім сервісом, або той сервіс на данний момент не працює, а на компі чи ноуті вже є встановлений Python. Поділюсь з вами ще одним скриптиком, яким часто користуюсь :)
Працює за допомогою бібліотеки pytubefix та утиліти ffmpeg (https://www.ffmpeg.org/download.html)
###importing packages
from pytubefix import YouTube
from pytubefix.cli import on_progress
import subprocess
import os
###url input from user
yt = YouTube(
str(input("Enter the URL of the video you want to download: \n>> ")), on_progress_callback = on_progress )
###extract only audio
data = yt.streams.filter(only_audio=True).first()
###check for destination to save file
print("Enter the destination (leave blank for current directory)")
destination = str(input(">> ")) or '.'
###download the file
out_file = data.download(output_path=destination)
###save the file
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
try:
subprocess.run(['ffmpeg', '-i', out_file, new_file])
except Exception as e:
print("Error happened:", str(e))
else:
os.remove(out_file)
#result of success
print(yt.title + " has been successfully downloaded.")
Ви скажете, тю, таких скриптів повно в мережі. Воно то й так, але не всі вони актуальні, та працюють, бо Youtube час від часу змінює свою політику. Тож актуальний код до вашої уваги :)
English version ( hi @justola1 :) ):
Sometimes you need to download some audio from YouTube, and it is either too long to use some third-party service, or that service is not working at the moment, and Python is already installed on your computer or laptop. I will share with you another script that I often use :)
Works with library pytubefix and ffmpeg framework (https://www.ffmpeg.org/download.html)
###importing packages
from pytubefix import YouTube
from pytubefix.cli import on_progress
import subprocess
import os
###url input from user
yt = YouTube(
str(input("Enter the URL of the video you want to download: \n>> ")), on_progress_callback = on_progress )
###extract only audio
data = yt.streams.filter(only_audio=True).first()
###check for destination to save file
print("Enter the destination (leave blank for current directory)")
destination = str(input(">> ")) or '.'
###download the file
out_file = data.download(output_path=destination)
###save the file
base, ext = os.path.splitext(out_file)
new_file = base + '.mp3'
try:
subprocess.run(['ffmpeg', '-i', out_file, new_file])
except Exception as e:
print("Error happened:", str(e))
else:
os.remove(out_file)
###result of success
print(yt.title + " has been successfully downloaded.")
You will say, huh, there are a lot of such scripts on the network. It is so, but not all of them are up-to-date, but they work, because Youtube changes its policy from time to time. So the current code is for your attention :)