使用pytube下载mp3格式的视频 [英] Download video in mp3 format using pytube

查看:121
本文介绍了使用pytube下载mp3格式的视频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用pytube用python下载youtube视频.到目前为止,我已经能够以mp4格式下载.

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

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

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.

如何直接以 .mp3 格式 将视频作为音频文件下载?请提供一些代码,因为我是刚接触此模块的人.

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.

推荐答案

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

How can I download the video as an audio file, in .mp3 format directly?

恐怕你做不到.唯一可直接下载的文件是 yt.streams.all()下列出的文件.

I'm afraid you can't. The only files available for direct download are the ones which are listed under yt.streams.all().

但是,将下载的音频文件从 .mp4 转换为 .mp3 格式很简单.例如,如果您安装了 ffmpeg ,则从终端运行此命令可以解决问题(假设您正在在下载目录中):

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

或者,您可以使用Python的 subprocess 模块以编程方式执行ffmpeg命令:

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

删除了对 subprocess.call 的提及.使用 subprocess.run (除非您使用的是Python 3.4或更低版本)

Removed mention of subprocess.call. Use subprocess.run (unless you're using Python 3.4 or below)

这篇关于使用pytube下载mp3格式的视频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆