I have been using pytube to download youtube videos in python. So far I have been able to download in mp4 format.
yt = pytube.YouTube("https://www.youtube.com/watch?v=WH7xsW5Os10")
vids= yt.streams.all()
for i in range(len(vids)):
print(i,'. ',vids[i])
vnum = int(input("Enter vid num: "))
vids[vnum].download(r"C:\YTDownloads")
print('done')
I managed to download the 'audio' version, but it was in .mp4
format. I did try to rename the extension to .mp3
, and the audio played, but the application (Windows Media Player) stopped responding and it began to lag.
How can I download the video as an audio file, in .mp3
format directly? Please provide some code as I am new to working with this module.
Answers 14 : of Download video in mp3 format using pytube first() # check for destination to save file print("Enter the destination (leave blank for current directory)") destination = str(input(">> ")) or '. ' # download the file out_file = video. download(output_path=destination) # save the file base, ext = os. path.
YouTube Video Downloader API enables users to convert Video into MP4, MP3, M4A formats using one endpoint. Get various video qualities such as 144p, 360p, and 720p. Using this API you can download videos with or without audio.
How can I download the video as an audio file, in .mp3 format directly?
I'm afraid you can't. The only files available for direct download are the ones which are listed under yt.streams.all()
.
However, it is straightforward to convert the downloaded audio file from .mp4
to .mp3
format. For example, if you have ffmpeg installed, running this command from the terminal will do the trick (assuming you're in the download directory):
$ ffmpeg -i downloaded_filename.mp4 new_filename.mp3
Alternatively, you can use Python's subprocess
module to execute the ffmpeg command programmatically:
import os
import subprocess
import pytube
yt = pytube.YouTube("https://www.youtube.com/watch?v=WH7xsW5Os10")
vids= yt.streams.all()
for i in range(len(vids)):
print(i,'. ',vids[i])
vnum = int(input("Enter vid num: "))
parent_dir = r"C:\YTDownloads"
vids[vnum].download(parent_dir)
new_filename = input("Enter filename (including extension): ")) # e.g. new_filename.mp3
default_filename = vids[vnum].default_filename # get default name using pytube API
subprocess.run([
'ffmpeg',
'-i', os.path.join(parent_dir, default_filename),
os.path.join(parent_dir, new_filename)
])
print('done')
EDIT: Removed mention of subprocess.call
. Use subprocess.run
(unless you're using Python 3.4 or below)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With