如何从含单个视频的目录自动读取视频并转换为音频文件
Fix: Auto-Convert Single Video in Directory to Audio
Let's get your code working to automatically target directories with exactly one video file (supporting .MOV, .mp4, etc.) and convert it to audio. Here's what was off in your original code, plus the corrected version:
Key Issues in Your Current Code
- You were using
video(the frame data returned bycap.read()) instead of the actual video file path (vid) when building the ffmpeg command — that's why it worked with manual input but not the glob result. - Your glob only targets .MOV files, but you mentioned wanting to support mp4 too.
- There's no check to ensure the directory has exactly one video file, which is your core requirement.
Corrected Code
import glob import subprocess # Define your target directory target_dir = '/home/qwickbit/Desktop/Qwickbit/Tennis_OpenCV/' # Match multiple video extensions (add more if needed, e.g., .MP4, .avi) video_files = glob.glob(f'{target_dir}*.{MOV,mp4,mov,MP4}') # Check if there's exactly one video file in the directory if len(video_files) == 1: vid_path = video_files[0] minLength = 50 minBF = 1 audio_output = f"Audio_file{minLength}{minBF}.wav" # Build the correct ffmpeg command using the actual video file path audio_convert_cmd = f"ffmpeg -i '{vid_path}' -ac 1 -f wav -vn '{audio_output}'" # Execute the command subprocess.call(audio_convert_cmd, shell=True) print(f"Successfully converted {vid_path} to {audio_output}") elif len(video_files) == 0: print("No video files found in the directory.") else: print(f"Found {len(video_files)} video files — expected exactly one.")
What This Does
- Multi-format support: The glob pattern matches case variations of .MOV and .mp4 files (add other extensions like .avi inside the curly braces if needed).
- Single file validation: Ensures we only proceed if the directory has exactly one video, aligning with your requirement.
- Correct file path usage: Uses
vid_path(the actual file path from glob) instead of frame data for the ffmpeg command — this fixes the core error in your original code. - User feedback: Prints clear status messages so you know if the conversion worked, or why it didn't.
Optional Tweaks
- If you need to scan subfolders recursively for the single video, add
recursive=Truetoglob.glob()and adjust the path tof'{target_dir}/**/*.{MOV,mp4,mov,MP4}' - Wrap file paths in single quotes in the ffmpeg command (like in the code above) to handle spaces in file/directory names.
内容的提问来源于stack exchange,提问作者Manohar Sonwan
相关产品推荐
相关产品推荐

