python
主页 > 脚本 > python >

python3获取视频文件播放时长的三种方法

2024-04-19 | 佚名 | 点击:

方法一:VideoFileClip

1

2

3

4

5

6

from moviepy.editor import VideoFileClip

 

 

def get_duration_from_moviepy(url):

    clip = VideoFileClip(url)

    return clip.duration

方法二:CV2

最快。

下载安装:https://github.com/opencv/opencv/releases

1

pip install opencv-python

1

2

3

4

5

6

7

8

9

10

11

import cv2

 

 

def get_duration_from_cv2(filename):

  cap = cv2.VideoCapture(filename)

  if cap.isOpened():

    rate = cap.get(5)

    frame_num =cap.get(7)

    duration = frame_num/rate

    return duration

  return -1

方法三:FFmpeg

1

pip install ffmpy3

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

import ffmpy3

 

 

def get_duration_from_ffmpeg(url):

    tup_resp = ffmpy3.FFprobe(

        inputs={url: None},

        global_options=[

            '-v', 'quiet',

            '-print_format', 'json',

            '-show_format', '-show_streams'

        ]

    ).run(stdout=subprocess.PIPE)

 

    meta = json.loads(tup_resp[0].decode('utf-8'))

    return meta['format']['duration']

速度比较

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

import json

import subprocess

import time

import cv2

import ffmpy3

from moviepy.editor import VideoFileClip

 

 

ls = [

"https://test/1.mp4",

"http://test/2.mp4",

"https://test/3.mp4"

]

 

 

def get_duration_from_cv2(filename):

  cap = cv2.VideoCapture(filename)

  if cap.isOpened():

    rate = cap.get(5)

    frame_num =cap.get(7)

    duration = frame_num/rate

    return duration

  return -1

 

 

def get_duration_from_moviepy(url):

    clip = VideoFileClip(url)

    return clip.duration

 

 

def get_duration_from_ffmpeg(url):

    tup_resp = ffmpy3.FFprobe(

        inputs={url: None},

        global_options=[

            '-v', 'quiet',

            '-print_format', 'json',

            '-show_format', '-show_streams'

        ]

    ).run(stdout=subprocess.PIPE)

 

    meta = json.loads(tup_resp[0].decode('utf-8'))

    return meta['format']['duration']

 

 

for u in ls:

    t1 = time.time()

    p = get_duration_from_cv2(u)

    t2 = time.time()

    print('CV2 Duration: ', p, ' Time: ', t2 - t1)

 

    t1 = time.time()

    p = get_duration_from_moviepy(u)

    t2 = time.time()

    print('Moviepy Duration: ', p, ' Time: ', t2 - t1)

 

    t1 = time.time()

    p = get_duration_from_ffmpeg(u)

    t2 = time.time()

    print('FFMPEG Duration: ', p, ' Time: ', t2 - t1)

    print()

原文链接:
相关文章
最新更新