Як скачати аудіо з Youtube за допомогою Python. / How to download any audio from youtube with Python

avatar
(Edited)

Іноді буває потрібно закачати якесь аудіо з ютуб, і воно або надто довге щоб користуватись якимось стороннім сервісом, або той сервіс на данний момент не працює, а на компі чи ноуті вже є встановлений 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 :)



0
0
0.000
10 comments
avatar

Wow, love this post It’s been handpicked and curated by the awesome Bilpcoin team—we’re so happy to support amazing content like this! If you’d like to join us in spreading the positivity, feel free to delegate some Hive Power to this account. Every bit helps us curate and uplift even more creators in the community By adding #bilpcoin or #bpc to original posts, you can earn BPC tokens
https://hive.blog/hive-167922/@bpcvoter2/calling-all-music-artists-on-hive-elevate-your-sound-with-ai-infused-beats

By adding #bilpcoin or #bpc to original posts, you can earn BPC tokens

https://peakd.com/hive-140084/@bpcvoter1/my-way-keni-bpc-ai-music

https://peakd.com/hive-126152/@bpcvoter2/dear-themarkymark-buildawhale-gogreenbuddy-usainvote-ipromote-and-whoever-else-is-involved-in-this-scheme-you-call-us-nutty-as

https://peakd.com/hive-167922/@bilpcoinbpc/exploring-the-possibilities-of-ai-art-with-bilpcoin-nfts-episode-102-buildawhale-scam-farm-on-hive-and-dear-steevc

https://peakd.com/hive-133987/@bilpcoinbpc/comprehensive-analysis-of-punkteam-s-wallet-transactions

https://hive.blog/hive-163521/@bpcvoter1/deep-dive-into-meritocracy-s-activity-history-and-blockchain-audit

https://www.publish0x.com/the-dark-side-of-hive/to-downvoters-scammers-and-farmers-on-hive-the-time-to-chang-xmjzrmp

https://peakd.com/hive-163521/@bpcvoter3/themarkymark-we-ve-exposed-your-actions-repeatedly-how-you-and-your-army-of-bots-manipulate-rewards-to-benefit-yourselves-it-s

https://peakd.com/hive-168088/@bpcvoter3/the-shadow-matrix-a-tale-of-deceit-and-reckoning

Our move?
🔹 Unite voices: Use #bilpcoin or #bpc to highlight censorship & demand accountability.
🔹 Document abuse: Share evidence of unfair downvotes, self-voting scams, and double standards.
🔹 Push for reform: Advocate for transparent governance, vote caps, and community-driven rules.

Decentralization isn’t just a feature—it’s a fight. Let’s model fairness, rally allies, and pressure Hive to live up to its ideals.
https://peakd.com/hive-167922/@bpcvoter3/5m1kft-themarkymark-you-can-keep-pretending-to-be-oblivious-but-the-truth-is-out-you-ve-been-exposed-it-s-time-to-own-up-to-your

#StandForDecentralization #HiveTransparency

0
0
0.000
avatar

Congratulations @stranger27! You have completed the following achievement on the Hive blockchain And have been rewarded with New badge(s)

You published more than 650 posts.
Your next target is to reach 700 posts.

You can view your badges on your board and compare yourself to others in the Ranking
If you no longer want to receive notifications, reply to this comment with the word STOP

0
0
0.000
avatar

Ну от тепер прийдеться Python ставити 😀. Дякую, трохи поекспериментуємо...

0
0
0.000
avatar

трохи пофіксив відображення коду, бо редактор не показува відступи, а вони важливі

0
0
0.000
avatar

Thank you for your witness vote!
Have a !BEER on me!
To Opt-Out of my witness beer program just comment STOP below

0
0
0.000
avatar

Without login or register? Looks really good

0
0
0.000