Prerequisites

  • Python 3
  • ffmpeg

Python Script to Download Youtube Video

download.py

from pytube import YouTube

def Download(link):
    youtubeObject = YouTube(link)
    youtubeObject = youtubeObject.streams.get_highest_resolution()
    try:
        youtubeObject.download()
    except:
        print("An error has occurred")
    print("Download is completed successfully")


link = input("Enter the YouTube video URL: ")
Download(link)

Python Script to Convert Downloaded Video File to mp3

main.py

import os
import subprocess
def convert_vid():
    print("video conversion")
    vids = dict({"Title of Video": ("00:01:00","00:02:00"),
                 })
    for key in vids:
        vid_name = key+".mp4"
        out_name = key+".mp3"
        out_trimmed_name = key+"_trimmed.mp3"
        val = vids[key]
        subprocess.call(['ffmpeg','-i',vid_name,out_name])
        subprocess.call(['ffmpeg', '-i', out_name, '-ss', val[0], '-to', val[1], '-acodec', 'copy', out_trimmed_name])

if __name__ == '__main__':
    convert_vid()

See repository.

Documentation

  • https://itsfoss.com/download-youtube-linux/
  • https://www.freecodecamp.org/news/python-program-to-download-youtube-videos/
  • https://pytube.io/en/latest/
  • https://www.geeksforgeeks.org/pytube-python-library-download-youtube-videos/
  • https://www.youtube.com/watch?v=C0PJZov8smo
  • https://developers.google.com/youtube/v3/docs/playlistItems/list
  • https://github.com/vastevenson/python-youtube-mp3-downloader