Video programında ses ve video dosyası indirmek ile ilgili olan kodu geliştirmek için öneri

omersseven

Decapat
Katılım
1 Ocak 2022
Mesajlar
244
Daha fazla  
Cinsiyet
Erkek
Merhaba ben 16 yaşındayım ve proje ararken YouTube"den video indirme ile alakalı bir eklenti keşfettim ve dedim ki ben bunu geliştireyim. Biraz üzerinde çalıştım ama halen istediğim seviyede değil ve bazı hatalar alıyorum. Belki aranızda ilgilenen ve yardımcı olmak isteyen birisi olur diye burada paylaşıp yardım alabileceğimi düşündüm.

Kod hakkında biraz bilgi vereyim video programında hem sadece video, ses dosyası indirmek için iki kısım bulunuyor video indirmek istediğinde 720p ve 360p arasında kalitelerde video indirebiliyordun. Başka kalitede indirmek istediğinde görüntü var ama ses yoktu. Ben de biraz araştırdım yabancı bir kaynakta ses ve video dosyasını ayrı indirip daha sonra birleştirme fikrini gördüm. Bunu nasıl yaparım diye baktığımda "moviepy" eklentisi ile bunu yapabileceğimi gördüm ve denedim oldu. Daha sonra uygulamayı CMD üzerinde çalıştırınca sorun almaya başladım ve iş çıkmaza girdi gibi hissetim ve zorlanmaya başladım. O yüzden sizlerden yardım istiyorum.

Python:
import pytube.
from tqdm import tqdm.
from pathlib import Path.
from pytube.exceptions import PytubeError.
from moviepy.editor import VideoFileClip, AudioFileClip.
import moviepy.
import os.
import re.

def clean_filename(filename):
 return re.sub(r'[^\w\-_\.]', '', filename)

def get_resolutions(streams):
 resolutions = []
 for stream in streams:
 if stream.resolution not in resolutions:
 resolutions.append(stream.resolution)
 return resolutions.

def download_video_and_audio(url, output_path):
 try:
 yt = pytube.YouTube(url)
 streams = yt.streams.all()
 resolutions = get_resolutions(streams)

 print("\nAvailable video qualities:")
 for i, resolution in enumerate(resolutions, start=1):
 print(f"{i}. {resolution}")

 while True:
 try:
 choice = int(input("Select the quality (1-{}): ".format(len(resolutions))))
 if 1 <= choice <= len(resolutions):
 break.
 else:
 print("Invalid choice. Please select a number between 1 and {}.".format(len(resolutions)))
 except ValueError:
 print("Invalid input. Please enter a number.")

 resolution = resolutions[choice - 1]
 streams = yt.streams.filter(res=resolution, file_extension='mp4')

 if not streams:
 print("No streams found for the selected quality. Please choose a different quality.")
 return.

 selected_stream = streams.first()

 print(f"\nDownloading {resolution} video and audio...")
 with tqdm(total=selected_stream.filesize, unit='B', unit_scale=True, desc="Download progress") as progress_bar:
 video_file = selected_stream.download(output_path=output_path, filename=clean_filename(f"{yt.title}_{resolution}_video.mp4"))
 audio = yt.streams.filter(only_audio=True).first()
 audio_file = audio.download(output_path=output_path, filename=clean_filename(f"{yt.title}_{resolution}_audio.mp3"))
 progress_bar.update(selected_stream.filesize)
 print("\nVideo and audio downloaded successfully!")
 print("The video file has been saved to:", video_file)
 print("The audio file has been saved to:", audio_file)
 return video_file, audio_file.
 except PytubeError as e:
 print("An error occurred:", e)

def merge_video_audio(video_path, audio_path, output_path):
 try:
 video_clip = VideoFileClip(str(video_path))
 audio_clip = AudioFileClip(str(audio_path))
 video_clip = video_clip.set_audio(audio_clip)
 video_clip.write_videofile(str(output_path))
 video_clip.close()
 audio_clip.close()
 print("Video and audio files merged successfully!")
 except Exception as e:
 print("An error occurred during merging:", e)

def delete_files(*files):
 for file in files:
 try:
 if os.path.exists(file):
 os.remove(file)
 print(f"{file} deleted successfully.")
 except Exception as e:
 print(f"Error occurred while deleting {file}: {e}")

def get_valid_url():
 while True:
 url = input("Enter the URL of the YouTube media you want to download: ")
 if url.startswith("https://www.youtube.com"):
 return url.
 else:
 print("Invalid YouTube URL. Please enter a valid YouTube URL.")

def download_audio(url, output_path):
 try:
 yt = pytube.YouTube(url)
 audio_streams = yt.streams.filter(only_audio=True)
 print("\nAvailable audio qualities:")
 for i, stream in enumerate(audio_streams, start=1):
 print(f"{i}. {stream.abr} - {stream.mime_type}")

 while True:
 try:
 choice = int(input("Select the audio quality (1-{}): ".format(len(audio_streams))))
 if 1 <= choice <= len(audio_streams):
 break.
 else:
 print("Invalid choice. Please select a number between 1 and {}.".format(len(audio_streams)))
 except ValueError:
 print("Invalid input. Please enter a number.")

 selected_audio = audio_streams[choice - 1]

 print(f"\nDownloading {selected_audio.abr} audio...")
 audio_file = selected_audio.download(output_path=output_path, filename=f"{yt.title}_{selected_audio.abr}_audio.mp3")
 print("\nAudio downloaded successfully!")
 print("The audio file has been saved to:", audio_file)
 return audio_file.
 except PytubeError as e:
 print("An error occurred:", e)

def menu():
 while True:
 print("\nWhat do you want to download?")
 print("1) Download video.")
 print("2) Download audio.")
 print("3) Exit")
 choice = input("Make your choice (1-3): ")
 if choice == "3":
 break.
 elif choice not in ["1", "2"]:
 print("Invalid choice. Please make a choice between 1 and 3.")
 continue.
 url = get_valid_url()
 try:
 if choice == "1":
 output_path = Path(input("Enter the directory to save files (default is Downloads): ") or Path.home() / "Downloads")
 video_file, audio_file = download_video_and_audio(url, output_path)
 merged_file = output_path / f"{Path(video_file).stem}_with_audio.mp4"
 merge_video_audio(video_file, audio_file, merged_file)
 delete_files(video_file, audio_file)
 elif choice == "2":
 output_path = Path(input("Enter the directory to save files (default is Downloads): ") or Path.home() / "Downloads")
 download_audio(url, output_path)
 except Exception as e:
 print("An error occurred:", e)

menu()

# © 2024 By Ömer Faruk Seven.
 

Yeni konular

Geri
Yukarı