Get the accurate duration of a video
This works for me:
import AVFoundation
import CoreMedia
...
if let url = Bundle.main.url(forResource: "small", withExtension: "mp4") {
let asset = AVAsset(url: url)
let duration = asset.duration
let durationTime = CMTimeGetSeconds(duration)
print(durationTime)
}
For the video here it prints "5.568" which is correct.
Edit from comments:
A video that returns 707
seconds when divided by 60 sec/min
is 11.78
. This is 11.78 minutes, or 11 minutes and 0.78min * 60sec/min = 47sec
, total is 11 min 47 sec
How to get the duration of video using OpenCV
OpenCV is not designed to explore video metadata, so VideoCapture
doesn't have API to retrieve it directly.
You can instead "measure" the length of the stream: seek to the end, then get the timestamp:
>>> import cv2 as cv
>>> v = cv.VideoCapture('sample.avi')
>>> v.set(cv.CAP_PROP_POS_AVI_RATIO, 1)
True
>>> v.get(cv.CAP_PROP_POS_MSEC)
213400.0
Checking shows that this sets the point after the last frame (not before it), so the timestamp is indeed the exact total length of the stream:
>>> v.get(cv.CAP_PROP_POS_FRAMES)
5335.0
>>>> v.get(cv.CAP_PROP_FRAME_COUNT)
5335.0
>>> v.set(cv.CAP_PROP_POS_AVI_RATIO, 0)
>>> v.get(cv.CAP_PROP_POS_FRAMES)
0.0 # the 1st frame is frame 0, not 1, so "5335" means after the last frame
How to get the duration of a video in Python?
You can use the external command ffprobe
for this. Specifically, run this bash command from the FFmpeg Wiki:
import subprocess
def get_length(filename):
result = subprocess.run(["ffprobe", "-v", "error", "-show_entries",
"format=duration", "-of",
"default=noprint_wrappers=1:nokey=1", filename],
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
return float(result.stdout)
Find Video Duration From Content-Length in NodeJS
You can use this npm module
It will help you to get the video length even from an url
const { getVideoDurationInSeconds } = require('get-video-duration');
getVideoDurationInSeconds('http://myvideourl.com/filename.mp4').then((duration) => {
console.log(duration)
})
Of course you can then convert it into milliseconds. (x1000).
Get video duration when input a video file
In modern browsers, You can use the URL API's URL.createObjectURL()
with an non appended video element to load the content of your file.
var myVideos = [];
window.URL = window.URL || window.webkitURL;
document.getElementById('fileUp').onchange = setFileInfo;
function setFileInfo() { var files = this.files; myVideos.push(files[0]); var video = document.createElement('video'); video.preload = 'metadata';
video.onloadedmetadata = function() { window.URL.revokeObjectURL(video.src); var duration = video.duration; myVideos[myVideos.length - 1].duration = duration; updateInfos(); }
video.src = URL.createObjectURL(files[0]);;}
function updateInfos() { var infos = document.getElementById('infos'); infos.textContent = ""; for (var i = 0; i < myVideos.length; i++) { infos.textContent += myVideos[i].name + " duration: " + myVideos[i].duration + '\n'; }}
<div id="input-upload-file" class="box-shadow"> <span>upload! (ღ˘⌣˘ღ)</span> <input type="file" class="upload" id="fileUp" name="fileUpload"></div><pre id="infos"></pre>
Is it possible to limit the video duration when selecting a video using `PHPickerViewController`?
Having a look at the documentation for PHPickerFilter
and the PHPickerViewController
I can't see any native way to filter by video length.
The best solution that I can think of to conform to the delegate PHPickerViewControllerDelegate
and check the video length after the user has selected it.
You haven't provided the rest of your code but you should conform to the PHPickerViewControllerDelegate
and implement the required method:
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
guard let provider = results.first?.itemProvider else { return }
provider.loadItem(forTypeIdentifier: UTType.movie.identifier, options: [:]) { (videoURL, error) in
// Check the video length here
}
}
}
See the above code for an example on how to load the video. From here you can follow some of the existing answers to see how to extract the video duration. If the video duration is within the bounds you want to filter for, copy it to an appropriate location using FileManager
and process it how you see fit, if it does not (IE it is too long, or too short for your liking), then discard it and tell the user using an alert / message.
Here is an example on how to get the duration of a video. Note: You just need to replace the references to urls to the videoURL
you have access to in the completion handler (See the comment).
Get the accurate duration of a video
One other solution is to use a more powerful photo picker from a 3rd party.
This has the downside of requiring the user to provide permission to their whole photo library (where as photo picker does not need to prompt for permission, as it is an iOS provided & sandboxed view controller). It also introduces another dependency into your app.
If these downside are okay for your use case, then this might be just what you're looking for.
Here is a library that provides some more powerful filters: https://github.com/Yummypets/YPImagePicker
See the "Video" section on the README. It allows you to specify minimum and maximum video duration.
Related Topics
Make a Uibarbuttonitem Disappear Using Swift iOS
Error: Use of Unresolved Identifier 'Process'
Convert a Custom Object to Data to Be Saved in Nsuserdefauts
For Loop Cycle Showing Always the Last Array Value Swift 3 After Http Request
Implementing a Drag-And-Drop Zone in Swift
Swiftui - Two Buttons in a List
Keyboard Overlaying Action Sheet in iOS 13.1 on Cncontactviewcontroller
Implementing Nscopying in Swift with Subclasses
Viewcontroller Slide Animation
Convert Character to Integer in Swift
Swiftyjson - Call Can Throw, But It Is Marked with 'Try' and the Error Is Not Handled
Swift Http Request Use Urlsession
Swift Enum Loses Initialized Values When Set as a Property