MmB*_*tte 4 python wav video-processing moviepy pytube
我正在尝试从视频中提取音频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
Run Code Online (Sandbox Code Playgroud)
You can get the URL of the stream and extract the audio using ffmpeg-python.
ffmpeg-python module executes FFmpeg as sub-process and reads the audio into memory buffer.
FFmpeg transcode the audio to PCM codec in a WAC container (in memory buffer).
The audio is read from stdout pipe of the sub-process.
这是一个代码示例:
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)
Run Code Online (Sandbox Code Playgroud)
笔记: