如何解决从 YouTube 视频中提取音频
我正在尝试从 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
解决方法
您可以使用 ffmpeg-python 获取流的 URL 并提取音频。
ffmpeg-python 模块将 FFmpeg 作为子进程执行,并将音频读入内存缓冲区。
FFmpeg 将音频转码为 WAC 容器中的 PCM 编解码器(在内存缓冲区中)。
音频从子进程的标准输出管道中读取。
这是一个代码示例:
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 命令行工具。
- 代码示例正在运行,但我不确定它的稳健性。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。