Download video in mp3 format using pytube

假如想象 提交于 2021-01-20 19:41:41

问题


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.


回答1:


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)




回答2:


I am assuming you are using Python 3 and pytube 9.x, you can use the filter method to "filter", the file extension you are interested in.

For example, if you would like to download mp4 video file format it would look like the following:

pytube.Youtube('url here').streams.filter(file_extension='mp4').first()

if you would like to pull audio it would look like the following:

pytube.Youtube('url here').streams.filter(only_audio=True).all()

Hope that helps anyone landing on this page; rather than converting unnecessarily.




回答3:


With this code you will download all the videos from a playlist and saving them with the title from youtube in mp4 and mp4 audio formats.

i used the code from @scrpy in this question and the hint from @Jean-Pierre Schnyder from this answer

import os
import subprocess
import re
from pytube import YouTube
from pytube import Playlist


path =r'DESTINATION_FOLER'
playlist_url = 'PLAYLIST_URL'

play = Playlist(playlist_url)

play._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)")
print(len(play.video_urls))
for url in play.video_urls:
    yt = YouTube(url)
    audio = yt.streams.get_audio_only()
    audio.download(path)
    nome = yt.title
    new_filename=nome+'.mp3'
    default_filename =nome+'.mp4'
    ffmpeg = ('ffmpeg -i ' % path default_filename + new_filename)
    subprocess.run(ffmpeg, shell=True)
         
    
print('Download Complete')



回答4:


here is a mildly more slim and dense format for downloading an mp4 video and converting from mp4 to mp3:

Download will download the file to the current directory or location of the program, this will also convert the file to mp3 as a NEW file.

from pytube import YouTube
import os
import subprocess
import time

while True:
    url = input("URL: ")

    # Title and Time
    print("...")
    print(((YouTube(url)).title), "//", (int(var1)/60),"mins")
    print("...")

    # Filename specification
    # Prevents any errors during conversion due to illegal characters in name
    _filename = input("Filename: ")

    # Downloading
    print("Downloading....")
    YouTube(url).streams.first().download(filename=_filename)
    time.sleep(1)

    # Converting
    mp4 = "'%s'.mp4" % _filename
    mp3 = "'%s'.mp3" % _filename
    ffmpeg = ('ffmpeg -i %s ' % mp4 + mp3)
    subprocess.call(ffmpeg, shell=True)

    # Completion
    print("\nCOMPLETE\n")

This is an infinite loop that will allow the renaming, download, and conversion of multiple URLs.




回答5:


You will need to install pytubemp3 (using pip install pytubemp3) latest version 0.3 + then

from pytubemp3 import YouTube 
YouTube(video_url).streams.filter(only_audio=True).first().download()


来源:https://stackoverflow.com/questions/47420304/download-video-in-mp3-format-using-pytube

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!