Spaces:
Sleeping
Sleeping
import pytube | |
import os | |
from pytube import YouTube | |
from pydub import AudioSegment | |
def download_and_compress_youtube_audio(youtube_url): | |
"""Downloads the audio from a YouTube video, compresses it, renames it to the first twelve characters, and returns the downloaded file path.""" | |
try: | |
# Create a YouTube object | |
yt = YouTube(youtube_url) | |
# Get the audio stream | |
audio = yt.streams.filter(only_audio=True).first() | |
# Download the audio | |
print("Downloading...") | |
audio.download() | |
# Get the original filename | |
original_filename = audio.default_filename | |
# Extract the first twelve characters and change the file extension to .mp3 | |
compressed_filename = original_filename[:12] + '_compressed.mp3' | |
# Load the downloaded audio file | |
audio_segment = AudioSegment.from_file(original_filename) | |
# Compress the audio file (e.g., by reducing the bitrate) | |
audio_segment.export(compressed_filename, format="mp3", bitrate="64k") | |
# Remove the original downloaded file | |
os.remove(original_filename) | |
print("Download and compression complete! Audio saved to:", compressed_filename) | |
return compressed_filename | |
except Exception as e: | |
print("An error occurred:", e) | |
return None | |
# Example usage | |
youtube_url = "https://www.youtube.com/watch?v=your_video_id" | |
download_and_compress_youtube_audio(youtube_url) | |