Skip to content

Instantly share code, notes, and snippets.

@mkeneqa
Forked from mdiller/mp3ytclipper.py
Last active April 8, 2021 00:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkeneqa/93ab3c1777e74d4dab83d3ce2341fdb2 to your computer and use it in GitHub Desktop.
Save mkeneqa/93ab3c1777e74d4dab83d3ce2341fdb2 to your computer and use it in GitHub Desktop.
Python script for downloading the audio of a Youtube video, clipping a certain section of it, adding a slight fade in and out, and saving the clip to a file.
#!/usr/bin/python3.5
#example usage: mp3ytclipper.py "https://www.youtube.com/watch?v=MgxK5vm6lvk" later 44.3 46.3
import sys, re, subprocess, youtube_dl, os
if len(sys.argv) != 5:
print("usage: mp3ytclipper.py <youtubeurl> <outfilename> <starttime> <endtime>")
exit()
def gettime(timestr):
parts = timestr.split(":")
if len(parts) == 2:
return (int(parts[0]) * 60) + float(parts[1])
if len(parts) == 1:
return float(parts[0])
raise ValueError("Only minutes:seconds supported")
def runcommand(commandarray):
return subprocess.check_output(commandarray, stderr=subprocess.STDOUT).decode("utf-8")
url = sys.argv[1]
outfile = sys.argv[2] + ".mp3"
start = gettime(sys.argv[3])
duration = gettime(sys.argv[4]) - start
options = {
'format': 'bestaudio/best',
'extractaudio' : True,
'audioformat' : "mp3",
'outtmpl': 'yt_audio/%(id)s.mp3',
'noplaylist' : True,
'nooverwrites': True,
}
with youtube_dl.YoutubeDL(options) as ydl:
video_id = ydl.extract_info(url, download=False).get("id", None)
video_file = "yt_audio/{}.mp3".format(video_id)
if not os.path.exists(video_file):
ydl.download([url])
fadeduration = 0.25
fadefilter = "afade=t=in:ss=0:d={0},afade=t=out:st={1}:d={0}".format(fadeduration, duration - fadeduration)
print("converting/cropping")
runcommand(["ffmpeg", "-ss", str(start), "-t", str(duration), "-y", "-i", video_file, "-af", fadefilter, outfile ])
print("playing...")
runcommand(["open", outfile])
from pywebio import start_server
from pywebio.input import input, FLOAT, TEXT, URL, TIME
from pywebio.output import put_text
import sys, re, subprocess, youtube_dl, os
import time
def Download(url, outfile, start=None, duration=None):
options = {
'format': 'bestaudio/best',
'extractaudio': True,
'audioformat': "mp3",
'outtmpl': 'yt_audio/%(id)s.mp3',
'noplaylist': True,
'nooverwrites': True,
}
with youtube_dl.YoutubeDL(options) as ydl:
video_id = ydl.extract_info(url, download=False).get("id", None)
video_file = "yt_audio/{}.mp3".format(video_id)
if not os.path.exists(video_file):
ydl.download([url])
fade_duration = .5
fade_filter = "afade=t=in:ss=0:d={0},afade=t=out:st={1}:d={0}".format(fade_duration, duration - fade_duration)
if start and duration:
runcommand(
["ffmpeg", "-ss", str(start), "-t", str(duration), "-y", "-i", video_file, "-af", fade_filter, "-b:a",
"256k", outfile])
else:
runcommand(["ffmpeg", "-y", "-i", video_file, "-af", fade_filter, "-b:a", "256k", outfile])
def runcommand(command_array):
return subprocess.check_output(command_array, stderr=subprocess.STDOUT).decode("utf-8")
def get_time(timestr):
parts = timestr.split(":")
if len(parts) == 2:
return (int(parts[0]) * 60) + float(parts[1])
if len(parts) == 1:
return float(parts[0])
raise ValueError("Only minutes:seconds supported")
def main():
# height = input("Your Height(cm):", type=FLOAT)
# weight = input("Your Weight(kg):", type=FLOAT)
yt_url = input("Enter Youtube URL: ", type=URL, required=True)
mp3_file = input("Enter Name of File: ", type=TEXT, required=True)
start_time = input("Start Time: ", type=TEXT, required=False, placeholder='0:00', )
end_time = input("End Time: ", type=TEXT, required=False, placeholder='3:30')
if start_time and end_time:
start_time = get_time(start_time)
duration = get_time(end_time) - start_time
Download(url=yt_url, outfile=mp3_file, start=start_time, duration=duration)
put_text('File Cut to Time')
else:
Download(url=yt_url, outfile=mp3_file)
put_text('Full File Availiable For Listening')
if __name__ == '__main__':
main()
# start_server(main, debug=True, port=8080)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment