使用 pytubefix 从 YouTube 下载视频并使用 moviepy 合并音轨

pytube 使用会报400错误, 需要用 pytubefix 替代.

from pathlib import Path
from pytubefix import YouTube
from pytubefix.cli import on_progress
from moviepy import VideoFileClip,AudioFileClip,CompositeAudioClip
import os

work_path = '/home/milton/WorkPython/temp/'

imgpath = Path(work_path)
imgpath.mkdir(exist_ok = True)

#url = 'https://www.youtube.com/watch?v=Uy4uEZV4jpo'
url = 'https://www.youtube.com/watch?v=PEH2FtIkAus'
yt = YouTube(url, on_progress_callback=on_progress)

streams = yt.streams
for i in streams:
    print(i)
#ys = streams.filter(resolution='1080p', mime_type='video/mp4').first()
ys = streams.get_highest_resolution()
print(ys)
#exit()
vfile = ys.download(output_path=work_path)
print(vfile)
os.rename(vfile, vfile + '.ori')

# Download audio and rename
afile = streams.filter(only_audio=True).first().download(output_path=work_path)
print(afile)

# Setting the audio to the video
videoclip = VideoFileClip(vfile + '.ori')
audioclip = AudioFileClip(afile)
new_audioclip = CompositeAudioClip([audioclip])
videoclip.audio = new_audioclip
videoclip.write_videofile(vfile)

# Delete video and audio to keep the result
#os.remove(vfile + '.ori')
#os.remove(afile)

posted on 2025-04-07 07:56  Milton  阅读(238)  评论(0)    收藏  举报

导航