Skip to content

Instantly share code, notes, and snippets.

@webserveis
Last active January 15, 2023 13:26
Show Gist options
  • Save webserveis/66c02d591433100e5fd36c8957a88a5f to your computer and use it in GitHub Desktop.
Save webserveis/66c02d591433100e5fd36c8957a88a5f to your computer and use it in GitHub Desktop.
Script convert youtube video to MP3 in Python
import os
from sty import fg, bg, ef, rs
from pytube import YouTube
from pathlib import Path
import re
import inquirer
def cError(text): return fg.red + text + fg.rs
def cWarging(text): return fg.da_yellow + text + fg.rs
def cOk(text): return fg.li_green + text + fg.rs
def cInfo(text): return fg.li_blue + text + fg.rs
def cHeader(text): return fg.magenta + text + fg.rs
def cDesc(text): return fg.li_grey + text + fg.rs
CURRENT_USER_HOME = os.path.expanduser('~')
VIDEO_FILE_PATH = os.path.join(CURRENT_USER_HOME, 'Videos', 'MusicVideos')
AUDIO_FILE_PATH = os.path.join(CURRENT_USER_HOME, 'Music', 'Downloaded')
# https://blog.balasundar.com/extract-audio-from-youtube-video-using-python
def yt_video_to_audio(video_link, outdir):
print(cInfo(f'Descargando video...'))
yt = YouTube(video_link)
# @ Extract audio with 160kbps quality from video
video = yt.streams.filter(
only_audio=True, file_extension='mp4').order_by('abr').desc().first()
# video = yt.streams.filter(abr='160kbps').last()
# Reemplazas con un - los caracteres ilegales del nombre
title = re.sub(r'[<>:"/\|*?]', "-", video.title)
# @ Downloadthe file
out_file = video.download(output_path=outdir, filename=f"{title}.mp4")
print(f"video descargado: '{video.default_filename}'")
try:
base, ext = os.path.splitext(out_file)
new_file = Path(f'{base}.mp3')
if os.path.exists(new_file):
os.remove(new_file) # file exits, delete it
os.rename(out_file, new_file)
# @ Check success of download
if new_file.exists():
print(cOk(f'{yt.title}.mp3'))
except Exception as e:
print(cError(f'error: {e}'))
def extract_youtube_video_ids(text):
video_id_list = []
youtube_regex = re.compile(
r"(https?://)?(www\.)?(youtube\.com|youtu\.?be)/.+")
matches = youtube_regex.finditer(text)
for match in matches:
video_url = match.group()
video_id = video_url.split("?v=")[-1]
video_id_list.append(video_id)
return video_id_list
def process_all_videos(video_list):
for i, video_id in enumerate(video_list):
video_uri = "https://www.youtube.com/watch?v=" + video_id
print(cDesc(f"#{i} vid: {video_uri}"))
yt_video_to_audio(video_uri, "audio")
# =========================== Dependencias =======================================
# py install sty
# py install pytube
# py install inquirer
# =========================== Settings Script =======================================
video_list = """
Aquí se puede añadir los enlaces de youtube, uno por linea
"""
# =========================== Start Main Script =======================================
print(cHeader("Video Yotubue to MP3 v1.0"))
video_list = extract_youtube_video_ids(video_list)
if not video_list:
print(cError("No hay videos por procesar"))
else:
print(cDesc(f"{len(video_list)} Videos para procesar"))
questions = [
inquirer.Confirm("continue", message="Quiere procesar los vídeos?")
]
answers = inquirer.prompt(questions)
if (answers['continue']):
print(cInfo("Se intentará extraer la máxima calidad del audio"))
process_all_videos(video_list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment