Skip to content

Instantly share code, notes, and snippets.

@jmilldotdev
Last active May 10, 2023 12:46
Show Gist options
  • Save jmilldotdev/b107f858729064daa940057fc9b14e89 to your computer and use it in GitHub Desktop.
Save jmilldotdev/b107f858729064daa940057fc9b14e89 to your computer and use it in GitHub Desktop.
Download Youtube audio, speed it up, and automatically copy it to iTunes
import argparse
import shutil
import ffmpy
import youtube_dl
itunes_folder = (
"/Path/To/Automatically Add to Music Folder"
)
class FilenameCollectorPP(youtube_dl.postprocessor.common.PostProcessor):
def __init__(self):
super(FilenameCollectorPP, self).__init__(None)
self.filenames = []
def run(self, information):
self.filenames.append(information["filepath"])
return [], information
def download_audio(url):
options = {
"format": "bestaudio/best",
"postprocessors": [
{
"key": "FFmpegExtractAudio",
"preferredcodec": "mp3",
"preferredquality": "320",
}
],
"outtmpl": "%(title)s.%(ext)s",
}
ydl = youtube_dl.YoutubeDL(options)
filename_collector = FilenameCollectorPP()
ydl.add_post_processor(filename_collector)
ydl.download([url])
return filename_collector.filenames[0]
def speed_up_audio(file_name, speed=2.0):
new_fname = f"{file_name.split('mp3')[0]}_sped_up.mp3"
ff = ffmpy.FFmpeg(
inputs={file_name: None},
outputs={new_fname: ["-filter:a", f"atempo={speed}"]},
)
ff.run()
return new_fname
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Download audio from YouTube")
parser.add_argument("url", help="URL of the YouTube video")
parser.add_argument("--speed", nargs="?", help="Speed of the audio", type=float)
args = parser.parse_args()
fname = download_audio(args.url)
new_fname = speed_up_audio(fname, args.speed)
shutil.copy(new_fname, itunes_folder)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment