FFMPEG执行异常:输入路径含空格时视频报错但音频正常如何解决
问题原因
核心问题出在subprocess.call()的使用方式和shell参数解析逻辑上:
- 你使用了
shell=True模式,将整条命令作为单字符串传入,shell会自行按空白符拆分解析参数。虽然你给输入路径加了引号,但pathlib路径对象转字符串、命令换行拼接时的空白干扰会导致转义失效,带空格的图片路径被拆分为多个独立参数,ffmpeg误将截断的路径片段识别为输出文件,因此抛出无法识别输出格式的报错。 - 音频带空格时能正常运行只是巧合:当图片路径无空格时,前半段命令解析正常,音频路径的转义刚好生效,本质上整条命令的参数解析逻辑完全不可靠,只要路径含空格、单引号、问号等特殊字符就会出问题。
解决方案
方案1:快速修复(现有代码打补丁)
给所有路径占位符外层统一加双引号,主动将Path对象转为字符串,避免拼接异常:
def makeAudioImgMovs(): randImgs = getImgs() compAudClips = makeAudioClips() audioJpgs = dict(zip(randImgs,compAudClips)) for jpg, aud in audioJpgs.items(): print(f'The img is {jpg}, the type of the img is {type(jpg)} the aud is {aud} the type of the aud is {type(aud)}') subprocess.call('ffmpeg -hide_banner -loglevel error -loop 1 -i "{0}" -i "{1}" \ -filter:v "fade=in:st=0:d=1, fade=out:st=10:d=1,scale=720:480:force_original_aspect_ratio=decrease,pad=720:480:(ow-iw)/2:(oh-ih)/2,setsar=1" \ -filter:a "afade=in:st=0:d=1, afade=out:st=10:d=1" \ -c:v libx264 -t 11 -pix_fmt yuv420p -preset faster -shortest -c:a aac "{2}.mp4"'.format(str(jpg),str(aud),str(timePath/(pathlib.Path(jpg).stem))),shell=True) makeAudioImgMovs()
方案2:最优实践(彻底解决路径解析问题)
取消shell=True,将命令拆分为参数列表传入subprocess,完全跳过shell解析步骤,无需额外转义就能兼容所有带特殊字符的路径:
def makeAudioImgMovs(): randImgs = getImgs() compAudClips = makeAudioClips() audioJpgs = dict(zip(randImgs,compAudClips)) for jpg, aud in audioJpgs.items(): print(f'The img is {jpg}, the type of the img is {type(jpg)} the aud is {aud} the type of the aud is {type(aud)}') output_path = str(timePath/(pathlib.Path(jpg).stem)) + ".mp4" subprocess.call([ "ffmpeg", "-hide_banner", "-loglevel", "error", "-loop", "1", "-i", str(jpg), "-i", str(aud), "-filter:v", "fade=in:st=0:d=1, fade=out:st=10:d=1,scale=720:480:force_original_aspect_ratio=decrease,pad=720:480:(ow-iw)/2:(oh-ih)/2,setsar=1", "-filter:a", "afade=in:st=0:d=1, afade=out:st=10:d=1", "-c:v", "libx264", "-t", "11", "-pix_fmt", "yuv420p", "-preset", "faster", "-shortest", "-c:a", "aac", output_path ]) makeAudioImgMovs()
内容的提问来源于stack exchange,提问作者Woolwit
相关产品推荐
相关产品推荐

