tring any song from youtube pyton code.
import os
import yt_dlp
from pydub import AudioSegment
import glob
# YouTube link and time parameters
youtube_url = "https://youtu.be/ZhDdEY5E-CU" # Telugu song
start_time = "00:00:00" # hh:mm:ss
end_time = "00:00:30" # hh:mm:ss
# File paths
temp_mp3 = "/content/temp_download.mp3"
output_mp3 = "/content/trimmed_song.mp3"
# Function to convert hh:mm:ss to milliseconds
def time_to_ms(time_str):
h, m, s = map(int, time_str.split(":"))
return (h * 3600 + m * 60 + s) * 1000
# Download and trim YouTube audio
def download_and_trim_youtube(url, start_time, end_time):
ydl_opts = {
'format': 'bestaudio/best',
'postprocessors': [{
'key': 'FFmpegExtractAudio',
'preferredcodec': 'mp3',
'preferredquality': '192',
}],
'outtmpl': temp_mp3.replace(".mp3", ""),
}
with yt_dlp.YoutubeDL(ydl_opts) as ydl:
ydl.download([url])
mp3_files = glob.glob("/content/*.mp3")
if not mp3_files:
raise Exception("No MP3 file downloaded")
downloaded_mp3 = max(mp3_files, key=os.path.getctime)
audio = AudioSegment.from_mp3(downloaded_mp3)
start_ms = time_to_ms(start_time)
end_ms = time_to_ms(end_time)
if end_ms <= start_ms or end_ms > len(audio):
raise ValueError("Invalid time range")
trimmed_audio = audio[start_ms:end_ms]
trimmed_audio.export(output_mp3, format="mp3", bitrate="192k")
if os.path.exists(downloaded_mp3):
os.remove(downloaded_mp3)
# Execute download and trim
download_and_trim_youtube(youtube_url, start_time, end_time)
print(f"✅ MP3 saved at: {output_mp3}")