How i can find duration of video using google photos API? (iOS/ Swift)

Viewed 136

The Google Photos library API does not return the duration of a video. API provides a lot of misc information like camera model and other stuff, but missing very basic things, like video duration, archive status and file size

1 Answers

If you have access to the file uri you could try something like this:

Android | Kotlin

fun getFileDuration(context: Context, uri: Uri): Int {
    try {
        val metadataRetriever = MediaMetadataRetriever()
        metadataRetriever.setDataSource(context, uri)
        val durationStr = metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)
        if (durationStr != null) return Integer.parseInt(durationStr)
    } catch (e: Exception) {
        e.printStackTrace()
        Log.w("getFileDuration", "Error getting duration of file with uri $uri with ${e.message}")
    }
    return 0
}

iOS | Swift

func getFileDuration(_ uri: URL) -> Int {
    let asset = AVURLAsset(url: uri)
    let audioDuration = asset.duration.seconds * 1000
    return Int(audioDuration)
}
Related