How to combine audio and video in Pytube?

Question:

I am trying to write a code to download YouTube videos using Pytube on Python 3.6. But for most videos progressive download(Audio and Video in same file) format is available only upto 360p. So I want to download audio and video files separately and combine it. I am able to to download the audio and video files. How can I combine the two file together?

Asked By: Nikith Clan

||

Answers:

Basically I don’t find any method to marge Audio and Video in Pytube but you can use ffmpeg for muxing.

First of all you have to install ffmpeg

  1. ffmpeg installation guide for Windows

  2. for Ubuntu just sudo apt install ffmpeg

Add a dependency ffmpeg-python a python wrapper of ffmpeg

  1. pip install ffmpeg-python

Now we are ready to go with this code snippet

import ffmpeg

video_stream = ffmpeg.input('Of Monsters and Men - Wild Roses.mp4')
audio_stream = ffmpeg.input('Of Monsters and Men - Wild Roses_audio.mp4')
ffmpeg.output(audio_stream, video_stream, 'out.mp4').run()

for more, ffmpeg-python API References

Answered By: Dipanjal Maitra

Merging audio and video using ffmpeg

Once you have downloaded both video and audio files (‘videoplayback.mp4’ and ‘videoplayback.m4a’ respectively), here’s how you can merge them into a single file:

In case of MP4 format (all, except 1440p 60fps & 2160p 60fps):

ffmpeg -i videoplayback.mp4 -i videoplayback.m4a -c:v copy -c:a copy output.mp4

In case of WebM format (1440p 60fps and 2160p 60fps):

ffmpeg -i videoplayback.webm -i videoplayback.m4a -c:v copy -c:a copy output.mkv

Wait until ffmpeg finishes merging audio and video into a single file named "output.mp4".

Answered By: Rishabh Bhardwaj

How do I convert the downloaded audio file to mp3?

you need to execute the following command in the Command Prompt window:

ffmpeg -i INPUT_FILE -ab BITRATE -vn OUTPUT_FILE

Example:

ffmpeg -i videoplayback.m4a -ab 128000 -vn music.mp3

Example:2 (without bit rate)

ffmpeg -i videoplayback.m4a -vn music.mp3
Answered By: Rishabh Bhardwaj

If you keep getting a video without audio, that’s because of the adaptive streaming from pytube. A work-around is to download both video and audio… then merge them with ffpmeg.

For instance, something like this to get both audio and video (audio part adapted from here)

from pytube import YouTube
import os

youtube = YouTube('https://youtu.be/ksu-zTG9HHg')
video = youtube.streams.filter(res="1080p").first().download()
os.rename(video,"video_1080.mp4")
audio = youtube.streams.filter(only_audio=True)
audio[0].download()

and then the ffmpeg part (adapted from both here and here) you can set it up on Windows following this procedure and then run something like

ffmpeg -i video.mp4 -i audio.mp4 -c:v copy -c:a aac output.mp4
Answered By: Tiago Martins Peres