从YouTube视频中提取音频

4

我正在尝试从一个 pytube 视频中提取音频并将其转换成 wav 格式。为了从视频中提取音频,我尝试使用 moviepy,但是我找不到一种使用 VideoFileClip 从字节打开视频文件的方法。我不想保存文件而是直接读取它们。

我的尝试:

from pytube import YouTube
import moviepy.editor as mp

yt_video = BytesIO()
yt_audio = BytesIO()

yt = YouTube(text)
videoStream = yt.streams.get_highest_resolution()
videoStream.stream_to_buffer(yt_video) # save video to buffer

my_clip = mp.VideoFileClip(yt_video) # processing video 

my_clip.audio.write_audiofile(yt_audio) # extracting audio from video
1个回答

6
你可以使用ffmpeg-python模块来获取流的URL并提取音频。

ffmpeg-python模块将FFmpeg作为子进程执行,并将音频读入内存缓冲区。 FFmpeg会在内存缓冲区中将音频转码为PCM编解码器和WAC容器。
音频从子进程的stdout管道中读取。

以下是代码示例:

from pytube import YouTube
import ffmpeg

text = 'https://www.youtube.com/watch?v=07m_bT5_OrU'

yt = YouTube(text)

# https://github.com/pytube/pytube/issues/301
stream_url = yt.streams.all()[0].url  # Get the URL of the video stream

# Probe the audio streams (use it in case you need information like sample rate):
#probe = ffmpeg.probe(stream_url)
#audio_streams = next((stream for stream in probe['streams'] if stream['codec_type'] == 'audio'), None)
#sample_rate = audio_streams['sample_rate']

# Read audio into memory buffer.
# Get the audio using stdout pipe of ffmpeg sub-process.
# The audio is transcoded to PCM codec in WAC container.
audio, err = (
    ffmpeg
    .input(stream_url)
    .output("pipe:", format='wav', acodec='pcm_s16le')  # Select WAV output format, and pcm_s16le auidio codec. My add ar=sample_rate
    .run(capture_stdout=True)
)

# Write the audio buffer to file for testing
with open('audio.wav', 'wb') as f:
    f.write(audio)

注意事项:

  • 你可能需要下载FFmpeg命令行工具。
  • 代码示例可以工作,但我不确定它的健壮性如何。

我该如何将它保存到内存而无需下载任何东西? - MmBaguette
我不确定我能找到解决方案... 我有几个问题:1. 使用URL yt.streams.all()[0].url 是否正确? 2. 您想同时获取音频和视频,还是只需要音频? 3. 解决方案是否必须使用moviepy,还是可以使用其他包,如ffmpeg-python - Rotem
我使用的软件包并不重要,我只是想以.wav格式提取音频。你的解决方案只是我已经找到的另一种选择。我该如何在内存中完成同样的事情? - MmBaguette
我发布了一个读取WAV文件到内存的解决方案。 - Rotem
太棒了!非常感谢。我将字节结果转换为BytesIO流。 - MmBaguette

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接