Python 获取视频时长方法get video duration
Example 1
Source File: video2frame.py From video2frame with GNU General Public License v3.0 | 6 votes | ![]() ![]() |
def get_video_duration(video_file):
cmd = [
"ffmpeg",
"-i", str(video_file),
"-f", "null", "-"
]
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
result_all = ffmpeg_duration_template.findall(output.decode())
if result_all:
result = result_all[-1]
duration = float(result[0]) * 60 * 60 \
+ float(result[1]) * 60 \
+ float(result[2]) \
+ float(result[3]) * (10 ** -len(result[3]))
else:
duration = -1
return duration
Example 2
Source File: pyCrawler_function.py From weibo-crawler with MIT License | 6 votes | ![]() ![]() |
def get_video_duration(path_video):
'''Get the duration of a video.
Parameter:
path_video <str> - The path of the input video.
Return:
duration <str> - The duration of the input video formatted as 'hh:mm:ss.msec'.
'''
# Create the command for getting the information of the input video via ffprobe.
cmd = ['ffprobe', '-show_format', '-pretty', '-loglevel', 'quiet', path_video]
# Get the information of the input video via ffprobe command.
info_byte = check_output(cmd) # <bytes>
# Decode the information.
info_str = info_byte.decode("utf-8") # <str>
# Split the information.
info_list = re.split('[\n]', info_str)
# Get the duration of the input video.
for info in info_list:
if 'duration' in info:
# E.g., 'info' = 'duration=0:00:01.860000'.
duration = re.split('[=]', info)[1]
return duration
Example 3
Source File: utils.py From asammdf with GNU Lesser General Public License v3.0 | 6 votes | ![]() ![]() |
def get_video_stream_duration(stream):
with TemporaryDirectory() as tmp:
in_file = Path(tmp) / "in"
in_file.write_bytes(stream)
try:
result = subprocess.run(
[
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"default=noprint_wrappers=1:nokey=1",
f"{in_file}",
],
capture_output=True,
)
result = float(result.stdout)
except FileNotFoundError:
result = None
return result
Example 4
Source File: utils.py From SnapchatBot with MIT License | 5 votes | ![]() ![]() |
def get_video_duration(path):
result = subprocess.Popen(["ffprobe", path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
matches = [x for x in result.stdout.readlines() if "Duration" in x]
duration_string = re.findall(r'Duration: ([0-9:]*)', matches[0])[0]
return math.ceil(duration_string_to_timedelta(duration_string).seconds)
Example 5
Source File: process_video.py From mapillary_tools with BSD 2-Clause "Simplified" License | 5 votes | ![]() ![]() |
def get_video_duration(video_file):
"""Get video duration in seconds"""
try:
return float(FFProbe(video_file).video[0].duration)
except Exception as e:
print("could not extract duration from video {} due to {}".format(video_file, e))
return None
Example 6
Source File: video.py From edx-analytics-pipeline with GNU Affero General Public License v3.0 | 4 votes | ![]() ![]() |
def get_video_duration(self, youtube_id):
"""
For youtube videos, queries Google API for video duration information.
This returns an "unknown" duration flag if no API key has been defined, or if the query fails.
"""
duration = VIDEO_UNKNOWN_DURATION
if self.api_key is None:
return duration
# Slow: self.incr_counter(self.counter_category_name, 'Subset Calls to Youtube API', 1)
video_file = None
try:
video_url = "https://www.googleapis.com/youtube/v3/videos?id={0}&part=contentDetails&key={1}".format(
youtube_id, self.api_key
)
video_file = urllib.urlopen(video_url)
content = json.load(video_file)
items = content.get('items', [])
if len(items) > 0:
duration_str = items[0].get(
'contentDetails', {'duration': 'MISSING_CONTENTDETAILS'}
).get('duration', 'MISSING_DURATION')
matcher = re.match(r'PT(?:(?P<hours>\d+)H)?(?:(?P<minutes>\d+)M)?(?:(?P<seconds>\d+)S)?', duration_str)
if not matcher:
log.error('Unable to parse duration returned for video %s: %s', youtube_id, duration_str)
# Slow: self.incr_counter(self.counter_category_name, 'Quality Unparseable Response From Youtube API', 1)
else:
duration_secs = int(matcher.group('hours') or 0) * 3600
duration_secs += int(matcher.group('minutes') or 0) * 60
duration_secs += int(matcher.group('seconds') or 0)
duration = duration_secs
# Slow: self.incr_counter(self.counter_category_name, 'Subset Calls to Youtube API Succeeding', 1)
else:
log.error('Unable to find items in response to duration request for youtube video: %s', youtube_id)
# Slow: self.incr_counter(self.counter_category_name, 'Quality No Items In Response From Youtube API', 1)
except Exception: # pylint: disable=broad-except
log.exception("Unrecognized response from Youtube API")
# Slow: self.incr_counter(self.counter_category_name, 'Quality Unrecognized Response From Youtube API', 1)
finally:
if video_file is not None