《自拍教程72》Python批量重命名視頻文件,AV專家必備!

案例故事: 任何一款終端產品只要涉及視頻播放,就肯定涉及視頻的解碼播放測試,
作爲一名專業的多媒體測試人員,我們需要一堆的規範的標準視頻測試文件
但是發現視頻資源名字命名的很隨意比如:big_buck_bunny_720p_h264.mp4,
以上命名不能看出視頻文件的具體編碼規格,
測試經理要求我進行批量重命名工作,模板如下,
視頻流信息 + 音頻流信息 + 容器.容器
視頻編碼格式_規格_分辨率_幀率_視頻比特率_音頻編碼格式_採樣率_聲道數_音頻比特率_容器.容器
H.264_BPL3.2_1280x720_30fps_1024kbps_aac_44.1KHz_stereo_128Kbps_mp4.mp4

視頻編解碼相關參數


其中視頻流,主要是通過批量壓縮每一幀的圖片來實現視頻編碼(壓縮),
其主要涉及以下關鍵技術參數:

視頻技術參數 參數釋義 舉例
視頻編碼格式
(壓縮技術)
即將圖片數據壓縮的一類技術,
不同的編碼格式,
其壓縮率與壓縮效果不一樣。
H.265/H.264/H.263
Mpeg1/Mpeg2/Mpeg4,
WMV,Real,VP8,VP9
視頻分辨率
(單位:Pixel)
視頻裏的每一張圖片的分辨率
(圖片長像素點數量*圖片寬像素點數量)
4096×2160(4K), 1920x1080,
1280x720,720×480,
640x480, 320x480等
視頻幀率
(單位:fps)
每秒鐘的圖片數量,圖片就是幀,一幀代表一張圖片 12fps,24fps,30fps,60fps
視頻比特率
(單位:Kbps)
每秒鐘的視頻流所含的數據量,
大概等於 = 編碼格式壓縮比幀率分辨率
1Mbps,5Mbps, 10Mbps, 512Kbps等等。
視頻容器 文件後綴,將視頻流+音頻流封裝的一種文件格式 .mp4; .3gp; .mkv; .mov;
.wmv; .avi; .webm;
.rmvb; .rm; .ts;

準備階段
  1. 確保mediainfo.exe 命令行工具已經加入環境變量,查看其具體功能方法
  2. 以下是某個視頻文件的mediainfo信息, 都是文本,Python處理起來肯定很簡單的。
  3. 如果要進行批量重命名視頻,我們還是用輸入輸出文件架構,如下:

	+---Input_Video   #批量放入待命名的視頻
	|       1.mp4
	|       2.3gp
	|       
	+---Output_Video   #批量輸出已命名的視頻
	|     H.264_BPL3.2_1280x720_30fps_1024kbps_aac_44.1KHz_stereo_128Kbps_mp4.mp4
	|     Mpeg4_SPL1_640x480_12fps_512kbps_AAC_24KHz_stereo_56Kbps_3gp.3gp
	|
	\video_info.py  # 視頻流解析模塊
	\audio_info.py  # 音頻流解析模塊
	\rename_video.py  #Python重命名視頻的批處理腳本,雙擊運行即可


定義video_info.py模塊

由於涉及較複雜的代碼,建議直接用面向對象類的編程方式實現:

# coding=utf-8

import os
import re
import subprocess


class VideoinfoGetter():
    def __init__(self, video_file):
        '''判斷文件是否存在,如果存在獲取其mediainfo信息'''
        if os.path.exists(video_file):
            self.video_file = video_file
            p_obj = subprocess.Popen('mediainfo "%s"' % self.video_file, shell=True, stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
            self.info = p_obj.stdout.read().decode("utf-8")  # 解決非英文字符的編碼問題
        else:
            raise FileNotFoundError("Not this File!")  # 如果多媒體文件路徑不存在,必須中斷

    def get_video_codec(self):
        '''獲取視頻的編碼格式,比如H.264, Mpeg4, H.263等'''
        try:
            video_codec = re.findall(r"Codec ID\s+:\s(.*)", self.info)
            if (len(video_codec) >= 3):
                video_codec = video_codec[1].strip()
            elif (len(video_codec) == 2):
                video_codec = video_codec[0].strip()
            elif (len(video_codec) == 1):
                video_codec = video_codec[0].strip()
            else:
                video_codec = "undef"
        except:
            video_codec = "undef"
        return self.__format_video_codec(video_codec)

    def get_video_profile(self):
        '''獲取視頻編碼格式的規格,比如Main Profile Level 3.2'''
        try:
            v_profile = re.findall(r"Format profile\s+:\s(.*)", self.info)
            # print vprofile
            if (len(v_profile) == 3):
                video_profile = v_profile[1].strip()
            elif (len(v_profile) == 2):
                video_profile = v_profile[0].strip()
            elif (len(v_profile) == 1):
                video_profile = v_profile[0].strip()
            else:
                video_profile = "undef"
        except:
            video_profile = "undef"
        return self.__format_video_profile(video_profile)

    def get_video_fps(self):
        '''獲取視頻的幀率,比如60fps,30fps'''
        try:
            video_fps = re.findall(r'Frame rate\s+:\s(.*)', self.info)[0].strip()
            return self.__format_fps(video_fps)
        except:
            return "undef"

    def get_video_height(self):
        '''獲取視頻圖像的高度(寬方向上的像素點)'''
        try:
            video_height = re.findall(r"Height\s+:\s(.*) pixels", self.info)[0].strip()
            return video_height
        except:
            return "undef"

    def get_video_weight(self):
        '''獲取視頻圖像的寬度(長方向上的像素點)'''
        try:
            video_weight = re.findall(r"Width\s+:\s(.*) pixels", self.info)[0].strip()
            return video_weight
        except:
            return "undef"

    def get_video_bitrate(self):
        '''獲取視頻比特率,比如560kbps'''
        try:
            # print findall(r"Bit rate\s+:\s(.*)", self.info)
            video_bitrate = re.findall(r"Bit rate\s+:\s(.*)", self.info)[0].strip()
            return self.__format_bitrate(video_bitrate)
        except:
            return "undef"

    def get_video_container(self):
        '''獲取視頻容器,即文件後綴名,比如.mp4 ,.3gp'''
        _, video_container = os.path.splitext(self.video_file)
        if not video_container:
            raise NameError("This file no extension")
        audio_container = video_container.replace(".", "")
        return audio_container

    def __format_video_profile(self, info):
        '''格式化視頻的規格參數,比如,MPL3.2'''
        v_profile_level = None
        v_profile = None
        v_level = None
        if (re.match(r'(.*)@(.*)', info)):
            m = re.match(r'(.*)@(.*)', info)
            m1 = m.group(1)
            m2 = m.group(2)
            if (m1 == "Simple"):
                v_profile = "SP"
            elif (m1 == "BaseLine"):
                v_profile = "BP"
            elif (m1 == "Baseline"):
                v_profile = "BP"
            elif (m1 == "Advanced Simple"):
                v_profile = "ASP"
            elif (m1 == "AdvancedSimple"):
                v_profile = "ASP"
            elif (m1 == "Main"):
                v_profile = "MP"
            elif (m1 == "High"):
                v_profile = "HP"
            elif (m1 == "Advanced Profile"):
                v_profile = "AP"
            elif (m1 == "Simple Profile Low"):
                v_profile = "SPL"
            elif (m1 == "Simple Profile Main"):
                v_profile = "SPM"
            elif (m1 == "Main Profile Main"):
                v_profile = "MPM"
            else:
                v_profile = m1
            if (m2 == "0.0"):
                v_level = "L0.0"
            else:
                v_level = m2
            v_profile_level = v_profile + v_level

        elif (re.match(r"(.*)\s(.*)", info)):
            v_profile_level = re.sub(r"\s", "", info)
        else:
            v_profile_level = info
        return v_profile_level

    def __format_video_codec(self, info):
        '''格式化輸出視頻編碼格式'''
        v_codec = None
        if (info == "avc1"):
            v_codec = "H.264"
        elif (info == "AVC"):
            v_codec = "H.264"
        elif (info == "27"):
            v_codec = "H.264"
        elif (info == "s263"):
            v_codec = "H.263"
        elif (info == "20"):
            v_codec = "Mpeg4"
        elif (info == "DIVX"):
            v_codec = "DIVX4"
        elif (info == "DX50"):
            v_codec = "DIVX5"
        elif (info == "XVID"):
            v_codec = "XVID"
        elif (info == "WVC1"):
            v_codec = "VC1"
        elif (info == "WMV1"):
            v_codec = "WMV7"
        elif (info == "WMV2"):
            v_codec = "WMV8"
        elif (info == "WMV3"):
            v_codec = "WMV9"
        elif (info == "V_VP8"):
            v_codec = "VP8"
        elif (info == "2"):
            v_codec = "SorensonSpark"
        elif (info == "RV40"):
            v_codec = "Realvideo"
        else:
            v_codec = "undef"
        return v_codec

    def __format_fps(self, info):
        '''格式化輸出幀率'''
        if (re.match(r'(.*) fps', info)):
            m = re.match(r'(.*) fps', info)
            try:
                info = str(int(int(float(m.group(1)) + 0.5))) + "fps"
            except:
                info = "Nofps"
        else:
            info = "Nofps"
        return info

    def __format_bitrate(self, info):
        '''格式化輸出比特率'''
        if (re.match(r'(.*) Kbps', info)):
            info = re.sub(r'\s', "", info)
            m = re.match(r'(.*)Kbps', info)
            try:
                info = str(int(float(m.group(1)))) + "Kbps"
            except Exception as e:
                # print(e)
                info = "NoBit"
        else:
            info = "NoBit"
        return info

定義audio_info.py模塊

請參考文章《Python mediainfo批量重命名音頻文件》裏的audio_info.py

調用video_info.py, audio_info.py模塊

實現批量重命名視頻文件

# coding=utf-8

import os
import shutil
import video_info
import audio_info

curdir = os.getcwd()

input_video_path = curdir + "\\Input_Video\\"
filelist = os.listdir(input_video_path)
output_video_path = curdir + "\\Output_Video\\"

if (len(filelist) != 0):
    for i in filelist:
        video_file = os.path.join(input_video_path, i)

        # 先解析視頻流
        v_obj = video_info.VideoinfoGetter(video_file)
        vcodec = v_obj.get_video_codec()
        vprofile = v_obj.get_video_profile()
        vresoultion = v_obj.get_video_weight() + "x" + v_obj.get_video_height()
        vfps = v_obj.get_video_fps()
        vbitrate = v_obj.get_video_bitrate()
        vcontainer = v_obj.get_video_container()

        # 再解析音頻流
        a_obj = audio_info.AudioInfoGetter(video_file)
        acodec = a_obj.get_audio_codec()
        asample_rate = a_obj.get_audio_sample_rate()
        achannel = a_obj.get_audio_channel()
        abitrate = a_obj.get_audio_bitrate()

        # 重命名
        new_video_name = vcodec + "_" + vprofile + "_" + vresoultion + "_" + vfps + \
        "_" + vbitrate + "_" + acodec + "_" + asample_rate + "_" + achannel + "_" + abitrate + "_" + vcontainer + "." + vcontainer
        print(new_video_name)
        new_video_file = os.path.join(output_video_path, new_video_name)

        # 複製到新的路徑
        shutil.copyfile(video_file, new_video_file)  # 複製文件
else:
    print("It's a Empty folder, please input the audio files which need to be renamed firstly!!!")
os.system("pause")

本案例練手素材下載

包含:mediainfo.exe(更建議丟到某個環境變量裏去),
各種編碼格式的視頻文件,video_info.py模塊,audio_info.py模塊,rename_video.py批處理腳本
跳轉到自拍教程官網下載
運行效果如下:


小提示: 比如Android手機,Google推出了CDD(Compatibiltiy Definition Document兼容性定義文檔)
其第5部分,涉及了很多視頻編解碼格式的規定,比如H.264的規定:

這就是Android最主要的視頻編解碼測試需求。


更多更好的原創文章,請訪問官方網站:www.zipython.com
自拍教程(自動化測試Python教程,武散人編著)
原文鏈接:https://www.zipython.com/#/detail?id=ed62bec121074a25a402d9a0bd250271
也可關注“武散人”微信訂閱號,隨時接受文章推送。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章