How to get a list of key frames (sync frames) time stamps for a video file in Android?

Viewed 5754

Is there any API which can give me the list of time stamps of the key frames for the given video file in Android?

5 Answers

Building on @ryan gordon's solution. seekTo may seek to the same frame, even when SEEK_TO_NEXT_SYNC is specified. To avoid this, you can terminate once frames start repeating.

For example:

    private fun getSyncFrameTimestamps(source: MediaExtractor): List<Long> {
        val result = mutableListOf<Long>()

        var lastSampleTime = -1L
        var sampleTime = source.sampleTime

        while (sampleTime >= 0L && sampleTime != lastSampleTime) {
            if (source.sampleFlags and MediaExtractor.SAMPLE_FLAG_SYNC != 0) {
                result.add(sampleTime)
            }
            source.seekTo(sampleTime + 1L, MediaExtractor.SEEK_TO_NEXT_SYNC)
            lastSampleTime = sampleTime
            sampleTime = source.sampleTime
        }

        return result
    }

Note that before calling this, source should have the data source set, and video track selected.

Related