song mergeing 26th April, 25
# it worked mergeing 3 songs, with delimiter
import os
import yt_dlp
from pydub import AudioSegment
import glob
# List of YouTube links and their start-end times (MM:SS format)
youtube_clips = [
{"url": "https://www.youtube.com/shorts/Fzj8mKhHd68", "start": "00:00", "end": "00:16"},
{"url": "https://www.youtube.com/shorts/dm-ABBciR_I", "start": "00:00", "end": "00:27"},
{"url": "https://www.youtube.com/shorts/_kjLupg3OFE", "start": "00:00", "end": "00:15"}
]
# Temporary folder for downloads
temp_folder = "/content/temp/"
os.makedirs(temp_folder, exist_ok=True)
# Output final mp3 file
final_output_mp3 = "/content/final_output.mp3"
# Delimiter MP3 (your custom small song between clips)
delimiter_mp3_path = "/content/sankVast_delimeter.mp3"
# Function to convert MM:SS or HH:MM:SS to milliseconds
def time_to_ms(time_str):
parts = list(map(int, time_str.split(":")))
if len(parts) == 2:
m, s = parts
h = 0
elif len(parts) == 3:
h, m, s = parts
else:
raise ValueError("Invalid time format")
return (h * 3600 + m * 60 + s) * 1000
# Function to download and trim a clip
def download_and_trim_youtube(url, start_time, end_time, index):
temp_mp3_path = os.path.join(temp_folder, f"clip_{index}.mp3")
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'outtmpl': temp_mp3_path.replace(".mp3", ""),
'quiet': True,
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
downloaded_mp3 = max(glob.glob(temp_folder + "*.mp3"), key=os.path.getctime)
audio = AudioSegment.from_mp3(downloaded_mp3)
start_ms = time_to_ms(start_time)
end_ms = time_to_ms(end_time)
# Adjust end_ms if it exceeds audio length
if end_ms > len(audio):
print(f"⚠️ Warning: Requested end time {end_time} exceeds audio length. Adjusting to end of audio.")
end_ms = len(audio)
if end_ms <= start_ms:
raise ValueError(f"Invalid time range for clip {index}: End time must be after start time.")
trimmed_audio = audio[start_ms:end_ms]
trimmed_audio.export(temp_mp3_path, format="mp3", bitrate="192k")
return temp_mp3_path
# Load your custom delimiter
delimiter_audio = AudioSegment.from_mp3(delimiter_mp3_path)
# Process all clips
final_audio = AudioSegment.empty()
for idx, clip in enumerate(youtube_clips):
print(f"Processing Clip {idx+1}...")
trimmed_mp3 = download_and_trim_youtube(clip['url'], clip['start'], clip['end'], idx)
segment = AudioSegment.from_mp3(trimmed_mp3)
final_audio += segment
if idx != len(youtube_clips) - 1:
final_audio += delimiter_audio # Add your own delimiter song between clips
# Export final merged MP3
final_audio.export(final_output_mp3, format="mp3", bitrate="192k")
print(f"✅ Final MP3 saved at: {final_output_mp3}")
# Cleanup temporary files
for f in glob.glob(temp_folder + "*.mp3"):
os.remove(f)
os.rmdir(temp_folder)
print("🧹 Cleaned up temporary files.")