该代码可能是因为在Windows系统上使用了Linux/Unix的路径分隔符'//',需要将其改为Windows的路径分隔符''。具体修改方法如下:

  1. 将第6行的代码修改为:
dir_path = 'E:\home\up'
  1. 将第13行的代码修改为:
ts_file = os.path.join(os.path.dirname(l), os.path.basename(l).replace('.mp4', '.ts')).replace('/', '\')
  1. 将第15行的代码修改为:
concat_command = f'ffmpeg -i 'concat:{'|' .join([os.path.join(os.path.dirname(l), os.path.basename(l).replace('.mp4', '.ts')).replace('/', '\') for l in L])}' -acodec copy -vcodec copy -bsf:a aac_adtstoasc '{os.path.join(dir_path, 'output.mp4').replace('/', '\')}'
  1. 将第20行的代码修改为:
for ts_file in glob.glob(os.path.join(dir_path, '*.ts'.replace('/', '\'))):

完成以上修改后,代码应该可以在Windows系统上正常运行。

完整代码:

import os
import glob
from natsort import natsorted

# 存储当前文件夹下的所有mp4文件路径
L = []
dir_path = 'E:\home\up'
for root, dirs, files in os.walk(dir_path):
    files = natsorted(files)
    for file in files:
        # 只处理mp4文件
        if os.path.splitext(file)[1] == '.mp4':
            file_path = os.path.join(root, file)
            L.append(file_path)

# 生成ffmpeg命令
commands = []
for l in L:
    ts_file = os.path.join(os.path.dirname(l), os.path.basename(l).replace('.mp4', '.ts')).replace('/', '\')
    commands.append(f'ffmpeg -i '{l}' -vcodec copy -acodec copy -bsf:v h264_mp4toannexb '{ts_file}'')

concat_command = f'ffmpeg -i 'concat:{'|' .join([os.path.join(os.path.dirname(l), os.path.basename(l).replace('.mp4', '.ts')).replace('/', '\') for l in L])}' -acodec copy -vcodec copy -bsf:a aac_adtstoasc '{os.path.join(dir_path, 'output.mp4').replace('/', '\')}'

# 执行ffmpeg命令
for command in commands:
    os.system(command)

os.system(concat_command)

# 删除所有ts文件
for ts_file in glob.glob(os.path.join(dir_path, '*.ts'.replace('/', '\'))):
    os.remove(ts_file)
Python代码在Windows上报IndexError: list index out of range错误的解决方法

原文地址: https://www.cveoy.top/t/topic/nzTq 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录