0

I'm looking for the alternate of Movie like to get the duration of GIF. I tried in imageDecoder but I can't able to get the duration.

//Deprecated
val movie = Movie.decodeStream(`is`)
val duration = movie.duration()

1 Answers1

0

Movie probably still works even though it's deprecated. But if you're not going to go on to use that Movie instance to play the GIF, that's a bad way of getting the duration because it will have to load the entire thing when all you really need to find the duration is in the meta data at the beginning of the file.

You could use the Metadata Extractor library to do this.

Since it's reading from a file, it is blocking and should be done in the background. Here's an example using a suspend function to accomplish that.

/** Returns duration in ms of the GIF of the stream, 0 if it has no duration,
 * or null if it could not be read. */
suspend fun InputStream.readGifDurationOrNull(): Int? = withContext(Dispatchers.IO) {
    try {
        val metadata = ImageMetadataReader.readMetadata(this@readGifDurationOrNull)
        val gifControlDirectories = metadata.getDirectoriesOfType(GifControlDirectory::class.java)
        if (gifControlDirectories.size <= 1) {
            return@withContext 0
        }
        gifControlDirectories.sumOf {
            it.getInt(GifControlDirectory.TAG_DELAY) * 10 // Gif uses 10ms units
        }
    } catch (e: Exception) {
        Log.e("readGifDurationOrNull", "Could not read metadata from input", e)
        null
    }
}

Credit to this answer for how to get the appropriate duration info from the metadata.

Tenfour04
  • 59,798
  • 9
  • 62
  • 120