Python爬取視頻時長場景實踐示例
簡介:
在視頻相關測試場景下,例如:有時需要知道全部視頻的匯總時長,顯然一個個打開並且手工計算耗時耗力,我們可以通過編寫腳本進行快速匯總。
獲取視頻時長的方式
1、通過subprocess進行獲取。
2、通過moviepy庫中VideoFileClip獲取。
3、通過cv2庫獲取。
安裝
1、subprocess:無需安裝,Python內置。
2、moviepy:pip install moviepy。
3、cv2:pip install opencv-python
準備工序:
1、當前項目新增videos目錄。
2、you-get 下載幾個視頻。python:超實用下載工具you-get
如:下載瞭兩個短視頻
獲取視頻時長的3種方式對比
import cv2 import time import subprocess from moviepy.editor import VideoFileClip def video_duration_1(filename): start = time.time() result = subprocess.run(["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "default=noprint_wrappers=1:nokey=1", filename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) end = time.time() spend = end - start print("獲取視頻時長方法1耗時:", spend) return float(result.stdout) def video_duration_2(filename): start = time.time() clip = VideoFileClip(filename) end = time.time() spend = end - start print("獲取視頻時長方法2耗時:", spend) return float(clip.duration) def video_duration_3(filename): start = time.time() cap = cv2.VideoCapture(filename) if cap.isOpened(): rate = cap.get(5) frame_num = cap.get(7) duration = frame_num / rate end = time.time() spend = end - start print("獲取視頻時長方法3耗時:", spend) return duration return -1 if __name__ == '__main__': file = r".\videos\mda-mkbhvebqej3cw9yh.mp4" video_time_1 = video_duration_1(file) print(video_time_1) print("*" * 100) video_time_2 = video_duration_2(file) print(video_time_2) print("*" * 100) video_time_3 = video_duration_3(file) print(video_time_3)
執行源碼:
結論:
1、三種方式均可以正常獲取視頻時長,並且準確。
2、推薦使用cv2獲取視頻時長,耗時最短。
實踐案例:獲取文件夾內全部視頻總時長
import cv2 import os def video_duration(dir_name): sum_duration = 0 for root, dirs, files in os.walk(dir_name, topdown=False): for filename in files: cap = cv2.VideoCapture(dir_name + "\\" + filename) if cap.isOpened(): rate = cap.get(5) frame_num = cap.get(7) duration = frame_num / rate sum_duration += duration return sum_duration if __name__ == '__main__': file = r".\videos" total_video_time = video_duration(file) print(f"{file} 目錄下全部視頻總時長為:{total_video_time}秒")
以上就是Python獲取視頻時長場景實踐示例的詳細內容,更多關於Python獲取視頻時長的資料請關註WalkonNet其它相關文章!