使用PYTUBE下载MP3格式的视频



我一直在使用pytube在Python中下载YouTube视频。到目前为止,我已经能够以MP4格式下载。

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')

我设法下载了"音频"版本,但它以.mp4格式。我确实尝试将扩展名重命名为.mp3,并且播放了音频,但是应用程序(Windows Media Player)停止响应,并且开始滞后。

如何以.mp3格式直接下载视频作为音频文件?请提供一些代码,因为我是使用此模块的新手。

如何将视频作为音频文件下载,以.mp3格式直接

我恐怕你不能。唯一可直接下载的文件是在yt.streams.all()中列出的文件。

但是,将下载的音频文件从.mp4转换为.mp3格式很简单。例如,如果您已安装了FFMPEG,则从终端运行此命令将有效(假设您在下载目录中):

$ ffmpeg -i downloaded_filename.mp4 new_filename.mp3

另外,您可以使用Python的subprocess模块来编程执行FFMPEG命令:

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')

编辑:删除提及subprocess.call。使用subprocess.run(除非您使用Python 3.4或以下)

我假设您正在使用Python 3和 pytube 9.x ,您可以将过滤器方法使用" filter&quot",您感兴趣的文件扩展程序in。

例如,如果您想下载MP4视频文件格式,则看起来如下:

pytube.YouTube("url here").streams.filter(file_extension="mp4").first()

如果您想拉音频,则看起来如下:

pytube.YouTube("url here").streams.filter(only_audio=True).all()

希望可以帮助任何人降落在此页面上;而不是不必要地转换。

您需要安装Pytubemp3(使用pip install pytubemp3)最新版本0.3 然后

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

将视频作为音频下载,然后将音频扩展更改为mp3:

from pytube import YouTube
import os
url = str(input("url:- "))
yt = YouTube(url)
video = yt.streams.filter(only_audio=True).first()
downloaded_file = video.download()
base, ext = os.path.splitext(downloaded_file)
new_file = base + '.mp3'
os.rename(downloaded_file, new_file)
print("Done")

pytube不支持" mp3"格式,但您可以以WebM格式下载音频。以下代码证明了它。

    from pytube import YouTube
    yt = YouTube("https://www.youtube.com/watch?v=kn8ZuOCn6r0")
    stream = yt.streams.get_by_itag(251)

ITAG是独特的ID

    stream.download()

对于mp3,您必须将(MP4或WebM)文件格式转换为mp3。

使用此代码,您将从播放列表中下载所有视频,并从MP4和MP4音频格式中保存标题。

我在这个问题中使用了@scrpy的代码,以及 @jean-pierre schnyder的提示从这个答案

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')

这是一种略微苗条和密集的格式,用于下载MP4视频并从MP4转换为MP3:

下载将将文件下载到程序的当前目录或位置,这也将将文件转换为mp3作为新文件。

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("nCOMPLETEn")

这是一个无限循环,将允许重命名,下载和转换多个URL。

from pytube import YouTube
yt = YouTube(url)
yt.streams.get_audio_only().download(output_path='/home/',filename=yt.title)

pytube不支持" mp3"格式,但您可以以WebM格式下载音频。以下代码证明了它。

    from pytube import YouTube
    yt = YouTube("https://www.youtube.com/watch?v=kn8ZuOCn6r0")
    stream = yt.streams.get_by_itag(251)
    stream.download()

对于mp3,您必须将(MP4或WebM)文件格式转换为mp3。

这是我的解决方案:

import os
import sys
from pytube import YouTube
from pytube.cli import on_progress
PATH_SAVE = "D:Downloads"
yt = YouTube("YOUR_URL", on_progress_callback=on_progress)
#Download mp3
audio_file = yt.streams.filter(only_audio=True).first().download(PATH_SAVE)
base, ext = os.path.splitext(audio_file)
new_file = base + '.mp3'
os.rename(audio_file, new_file)
#Download Video
ys = yt.streams.filter(res="1080p").first()
ys.download(PATH_SAVE)

工作:Python v3.9.x和Pytube V11.0.1

尝试使用:


    from  pytube import YouTube
    import os
        
    link = input('enter the link: ')
    path = "D:\"                     #enter the path where you want to save your video
    video = YouTube(link)
    print( "title is : ", video.title)
     
#download video
    print("title is : ", video.title)
    video.streams.filter(only_audio=True).first().download( path , filename ="TemporaryName.Mp4" )
#remove caracters (" | , /  ..... ) from video title
    VideoTitle =  video.title
    VideoTitle = VideoTitle.replace('"' , " ")
    VideoTitle = VideoTitle.replace('|', " ")
    VideoTitle = VideoTitle.replace(',', " ")
    VideoTitle = VideoTitle.replace('/"' , " ")
    VideoTitle = VideoTitle.replace('\', " ")
    VideoTitle = VideoTitle.replace(':', " ")
    VideoTitle = VideoTitle.replace('*"' , " ")
    VideoTitle = VideoTitle.replace('?', " ")
    VideoTitle = VideoTitle.replace('<', " ")
    VideoTitle = VideoTitle.replace('>"' , " ")
#change name and converting Mp4 to Mp3
    my_file = path + "\" +  "TemporaryName.mp4"
    base = path + "\" + VideoTitle
    print("New Video Title is :" +VideoTitle)
    os.rename(my_file, base + '.mp3')
    print(video.title, ' nhas been successfully downloaded as MP3')

这是我的解决方案:

from os import path, rename
from pytube import YouTube as yt
formato = ""
descarga = desktop = path.expanduser("~/Desktop")
link = input("Inserte el enlace del video: ")
youtube = yt(link)
while formato != "mp3" and formato != "mp4":
    formato = input("¿Será en formato mp3 o mp4? ")

if formato == "mp4":
    youtube.streams.get_highest_resolution().download(descarga)
elif formato == "mp3":
    video = youtube.streams.first()
    downloaded_file = video.download(descarga)
    base, ext = path.splitext(downloaded_file)
    new_file = base + '.mp3'
    rename(downloaded_file, new_file)
print("Descarga completa!")
input("Presiona Enter para salir...")

这是我的解决方案。只需使用Pytube的文件名选项重命名下载内容的名称。

url = input("URL of the video that will be downloaded as MP^: ")
  try:
    video = yt(url)
    baslik = video.title
    print(f"Title: {baslik}")
    loc = input("Location: ")
    print(f"Getting ITAG info for {baslik}")
    for itag in video.streams.filter(only_audio=True): # It'll show only audio streams.
      print(itag)
    itag = input("ITAG secimi: ")
    print(f"{baslik} sesi {loc} konumuna indiriliyor.")
    video.streams.get_by_itag(itag).download(loc, filename=baslik + ".mp3") # And you can rename video by filename= option. Just add .mp3 extension to video's title.
    print("Download finished.")
  except:
    print("Enter a valid URL")
    sys.exit()

这对我来说很好:

pip install pytube
pip install os_sys

# importing packages
from pytube import YouTube
import os
  
# url input from user
yt = YouTube(
    str(input("paste your link")))
  
# extract only audio
video = yt.streams.filter(only_audio=True).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.splitext(out_file)
new_file = base + '.mp3'
os.rename(out_file, new_file)
  
# result of success
print(yt.title + " has been successfully downloaded.")

这是使用Pytube下载最高质量音乐的功能,并将其保存在所需目录中。

from pytube import YouTube
import os
from pathlib import Path

def youtube2mp3 (url,outdir):
    # url input from user
    yt = YouTube(url)
    ##@ Extract audio with 160kbps quality from video
    video = yt.streams.filter(abr='160kbps').last()
    ##@ Downloadthe file
    out_file = video.download(output_path=outdir)
    base, ext = os.path.splitext(out_file)
    new_file = Path(f'{base}.mp3')
    os.rename(out_file, new_file)
    ##@ Check success of download
    if new_file.exists():
        print(f'{yt.title} has been successfully downloaded.')
    else:
        print(f'ERROR: {yt.title}could not be downloaded!')

我有一种使用Pytube的MP3下载YouTube视频的更多Pythonic方法:

# Use PyTube to download a YouTube video, then convert to MP3 (if needed) using MoviePy
import pytube
from moviepy.editor import AudioFileClip
link = "your youtube link here"
fn = "myfilename.mp3"
yt = pytube.YouTube(str(link))
video = yt.streams.filter(only_audio=True).first()
out_file = video.download(output_path='.')
os.rename(out_file, fn)
# Check is the file a MP3 file or not
if not out_file.endswith('.mp3'):
    # File is not a MP3 file, then try to convert it (first rename it)
    dlfn = '.'.join(fn.split('.')[:-1]) + '.' + out_file.split('.')[-1]
    os.rename(fn, dlfn)
    f = AudioFileClip(dlfn)
    f.write_audiofile(fn)
    f.close()
    os.remove(dlfn)

代码写在python3中。确保安装库: python3 -m pip install pytube moviepyhightpy不支持每个音频文件,但它支持大多数:"空"MP4(仅具有音乐的MP4),wav等...

为什么转换为mp3很重要?许多人只是重命名文件,但是此不能转换文件!如果您使用vlc使用vlc,则VLC将播放文件不是作为MP3,而是作为原始格式播放。因此,如果您使用仅支持MP3的软件播放文件,则音频播放器将返回错误。

相关内容

  • 没有找到相关文章

最新更新