วิธีการคำนวณเวลาของวีดีโอในภาษา python
ในภาษา Python มีวีธีการคำนวณเวลา โดยจะการใช้ Json เข้ามาเกี่ยวข้องด้วยโดยจะเก็บข้อมูลต่าง แล้วจะมี library ที่ชื่อว่า subprocess เกี่ยวข้อง โดยการคำนวณเวลาในไฟล์เวลานั้นจะต้องทำการเรียกใช้หรือทำการ import เข้ามาใช้งานก่อนถึงจะทำงานได้
ก่อนที่จะไปเขียนมารู้จักความหมายพวกนี้กันก่อน
JSON (JavaScript Object Notation) รูปแบบการรับส่งข้อมูลคอมพิเตอร์ขนาดเล็ก เป็นภาษาที่อ่าน, เขียน และสร้างเป็นภาษาโปรแกรมที่เข้าใจง่าย ถูกสร้างขึ้นมาโดย ดักกลาส คลอฟอร์ด ต้นกำเนิดอยู่ในรูปแบบ ของ RFC 4627 and ECMA-404 JSON เป็นรูปแบบข้อความภาษาอิสระ
ขั้นตอนการเขียน
ให้ทำการ import library module ก่อน
import subprocess as sp
import json
จากนั้นให้สร้างฟังก์ชั่น probe
def probe(vid_file_path):
if type(vid_file_path) != str:
raise Exception('Gvie ffprobe a full file path of the video')
return
command = ["ffprobe",
"-loglevel", "quiet",
"-print_format", "json",
"-show_format",
"-show_streams",
vid_file_path
]
pipe = sp.Popen(command, stdout=sp.PIPE, stderr=sp.STDOUT)
out, err = pipe.communicate()
return json.loads(out)
สร้างฟังก์ชั่น duration เพื่อไว้สำหรับหาระยะเวลาของวีดีโอ
def duration(vid_file_path):
_json = probe(vid_file_path)
if 'format' in _json:
if 'duration' in _json['format']:
return float(_json['format']['duration'])
if 'streams' in _json:
# commonly stream 0 is the video
for s in _json['streams']:
if 'duration' in s:
return float(s['duration'])
จากนั้นทำการเรียกใช้ฟังก์ชั่น duration
# -*- coding=utf-8 -*-
import subprocess as sp
import json
def probe(vid_file_path):
if type(vid_file_path) != str:
raise Exception('Gvie ffprobe a full file path of the video')
return
command = ["ffprobe",
"-loglevel", "quiet",
"-print_format", "json",
"-show_format",
"-show_streams",
vid_file_path
]
pipe = sp.Popen(command, stdout=sp.PIPE, stderr=sp.STDOUT)
out, err = pipe.communicate()
return json.loads(out)
def duration(vid_file_path):
_json = probe(vid_file_path)
if 'format' in _json:
if 'duration' in _json['format']:
return float(_json['format']['duration'])
if 'streams' in _json:
# commonly stream 0 is the video
for s in _json['streams']:
if 'duration' in s:
return float(s['duration'])
time_vdo= duration('content2language.mp4') # pathของวีดีโอ
end_minute=int(time_vdo/60)
end_second = int(time_vdo%60)
print 'นาที : %d' %end_minute
print 'วินาที : %d' %end_second
ผลที่ได้ก็จะเป็น นาทีและ วินาทีของวีดีโอ ก็ทำอันที่เรียบร้อย
อ้างอิง
stackoverflow.(2551).How to get the duration of a video in Python?.[ออนไลน์].เข้าถึงได้จาก https://stackoverflow.com/questions/3844430/how-to-get-the-duration-of-a-video-in-python. [19 ส.ค. 2562]