本代码使用Python3和mediainfo工具,读取指定文件夹下的视频文件,并提取包括文件大小、时长、分辨率、码率、帧率等信息,并输出到Excel表格。

所需条件:

  1. 安装mediainfo软件
    • 从官网 https://mediaarea.net/en/MediaInfo/Download 下载适合自己系统的安装包进行安装。
    • 安装完成后,需要将安装路径中的mediainfo.exe所在的目录添加到系统环境变量中,以便在命令行中直接调用mediainfo命令。
  2. 安装openpyxl模块
    • 使用pip命令安装:pip install openpyxl

代码示例:

import os
import re
import subprocess
import openpyxl
import math
from openpyxl.styles import Font, PatternFill, Alignment


# 支持的视频格式
supported_formats = ['.mp4', '.avi', '.mkv', '.wmv', '.mov', '.flv', '.m2ts', '.ts', '.rm', '.rmvb',
                     '.vob', '.3gp', '.webm', '.hdmov', '.mp4v', '.mpv4', '.divx', '.xvid', '.f4v',
					 '.mpeg', '.asf', '.asx', '.m2t']
# 需要处理的视频文件夹
video_folder = input('请输入文件夹路径:')
# 输出Excel文件夹路径
excel_folder = '.'
# 输出Excel文件名
excel_file = 'video_info.xlsx'
# 正则表达式匹配码率数据中的空格
pattern = re.compile(r'(\d+)\s+(\d+)')
# 创建Excel文件
wb = openpyxl.Workbook()
ws = wb.active
ws.title = 'Video Info'


# 设置表头样式
header_font = Font(bold=True, color='800080')  # 紫色
header_fill = PatternFill('solid', fgColor='C5E0B4')
header_alignment = Alignment(horizontal='center', vertical='center')
headers = ['文件名', '文件路径', '格式', '大小', '时长', '分辨率', '码率', '帧率', '音频码率', '音频采样率', '音频语言', '压缩比率']
for col, header in enumerate(headers, start=1):
    cell = ws.cell(row=1, column=col, value=header)
    cell.font = header_font
    cell.fill = header_fill
    cell.alignment = header_alignment

# 锁定表头
ws.freeze_panes = 'A2'

# 获取视频文件列表(包括子目录)
video_files = []
for root, dirs, files in os.walk(video_folder):
    for file in files:
        for format in supported_formats:
            if file.endswith(format):
                video_files.append(os.path.join(root, file))
                break
# 遍历所有视频文件,获取视频信息、音频信息和音频语言,并写入Excel文件
for row, video_file in enumerate(video_files, start=2):
    # 获取文件名
    file_name = os.path.basename(video_file)

    # 获取文件大小并进行单位换算
    size = os.path.getsize(video_file)
    if size < 1024:
        size_str = f'{size} B'
    elif size < 1024 * 1024:
        size_str = f'{size / 1024:.2f} KiB'
    elif size < 1024 * 1024 * 1024:
        size_str = f'{size / 1024 / 1024:.2f} MiB'
    else:
        size_str = f'{size / 1024 / 1024 / 1024:.2f} GiB'

    # 使用mediainfo获取视频信息 / 音频信息和音频语言
    video_result = subprocess.run(['mediainfo', '--Inform=Video;%Format%|%Width%x%Height%|%BitRate/String%|%FrameRate%|%Duration/String3%', video_file], stdout=subprocess.PIPE)
    video_output = video_result.stdout.decode().strip()
    audio_result = subprocess.run(['mediainfo', '--Inform=Audio;%BitRate/String%|%SamplingRate/String%|%Language/String%', video_file], stdout=subprocess.PIPE)
    audio_output = audio_result.stdout.decode().strip()

    # 解析输出结果
    format, resolution, bitrate, framerate, duration = video_output.split('|')
    audiobitrate, audiosamplingrate, audiolang = audio_output.split('|')
    
    # 时长取整
    duration = duration.split('.')[0]
    h, m, s = duration.split(':')
    duration = f'{h}:{m}:{math.ceil(float(s))}'

    # 以分钟计算的时长
    duration_minutes = int(h) * 60 + int(m) + math.ceil(float(s)) / 60

    # 计算压缩比率
    ratio = round(duration_minutes / size * 1000000000, 2)

    # 使用正则表达式替换码率数据中第一个数字和第二个数字之间的空格
    bitrate = re.sub(pattern, r'\1\2', bitrate)
    
    # 写入Excel文件
    ws.cell(row=row, column=1, value=file_name)
    ws.cell(row=row, column=2, value=os.path.dirname(video_file)) # 写入文件夹路径
    ws.cell(row=row, column=3, value=format)
    ws.cell(row=row, column=4, value=size_str) # 写入文件大小
    ws.cell(row=row, column=5, value=duration)
    ws.cell(row=row, column=6, value=resolution)
    ws.cell(row=row, column=7, value=bitrate)
    ws.cell(row=row, column=8, value=framerate)
    ws.cell(row=row, column=9, value=audiobitrate)
    ws.cell(row=row, column=10, value=audiosamplingrate)
    ws.cell(row=row, column=11, value=audiolang)
    ws.cell(row=row, column=12, value=ratio)

    # 打印进度
    print(f'已处理 {row-1}/{len(video_files)} 视频个文件', end='\r')

# 自动调整列宽
for col in ws.columns:
    max_length = 0
    column = col[0].column_letter
    for cell in col:
        try:
            if len(str(cell.value)) > max_length:
                max_length = len(str(cell.value))
        except:
            pass
    adjusted_width = (max_length + 2)
    ws.column_dimensions[column].width = adjusted_width + 1

# 调整L列的列宽和对齐方式
l_col = ws['L']
max_length = 0
for cell in l_col:
    try:
        if len(str(cell.value)) > max_length:
            max_length = len(str(cell.value))
    except:
            pass
l_col_width = max_length + 5 # 列宽加5
ws.column_dimensions['L'].width = l_col_width
for cell in l_col:
    cell.alignment = Alignment(horizontal='left') # 左对齐

# 保存Excel文件
if not os.path.exists(excel_folder):
    os.makedirs(excel_folder)
excel_file_path = os.path.join(excel_folder, excel_file)
wb.save(excel_file_path)
print(f'已处理完所有视频文件,视频信息已保存到 {excel_file_path}')

代码功能:

  • 支持读取指定文件夹下的视频文件,并自动识别子目录。
  • 支持多种常见视频格式。
  • 使用mediainfo工具提取视频和音频信息。
  • 将提取的信息写入Excel表格。
  • 自动调整列宽,方便阅读。
  • 输出处理进度。
  • 代码中已包含详细注释,方便理解和修改。

使用方式:

  1. 将代码保存为py文件,例如video_info_extractor.py
  2. 在命令行中运行代码,并输入需要处理的视频文件夹路径。
  3. 代码会自动读取文件夹下的视频文件,并生成一个名为video_info.xlsx的Excel文件,保存在当前目录下。

注意:

  • 代码需要在安装了mediainfo和openpyxl模块的Python环境下运行。
  • mediainfo工具的路径需要添加到系统环境变量中。
  • 代码中支持的视频格式可以通过修改supported_formats变量进行调整。
  • 代码中提取的信息可以通过修改headers变量进行调整。

其他:

  • mediainfo是一款强大的多媒体信息提取工具,可以提取各种视频和音频文件的详细信息,例如编码格式、分辨率、码率、帧率、声道数等。
  • openpyxl是一个用于操作Excel文件的Python库,可以方便地读取、写入和修改Excel文件。

希望本代码能帮助您轻松提取视频信息!如有任何问题,欢迎留言反馈。

Python3代码在Win10环境下运行所需条件 - 视频信息提取工具

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

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