I'm using below code to retrieve video frame from remote url using MediaMetadataRetriever
but it lags and results in very low performant UI. How can I make it fast and efficient?
@Composable
private fun ContentItem(
modifier: Modifier = Modifier,
content: Content,
onClick: (Content) -> Unit
) {
when (content.type) {
ContentType.Image -> {
// handle image
}
ContentType.Video -> {
val bitmap = remember { mutableStateOf<Bitmap?>(null) }
LaunchedEffect(content) {
val retriever = MediaMetadataRetriever()
retriever.setDataSource(content.url)
// Retrieve frame at 1 second
bitmap.value = retriever.getFrameAtTime(
1000000,
MediaMetadataRetriever.OPTION_CLOSEST_SYNC
)
retriever.release()
}
bitmap.value?.let {
Image(
modifier = modifier,
bitmap = it.asImageBitmap(),
contentDescription = null
)
}
}
}
}
CodePudding user response:
Instead of doing heavy work on ui thread you can use withContext
and Dispatchers.Default
as
LaunchedEffect(content) {
withContext(Dispatchers.Default){
val retriever = MediaMetadataRetriever()
retriever.setDataSource(content.url)
// Retrieve frame at 1 second
bitmap.value = retriever.getFrameAtTime(
1000000,
MediaMetadataRetriever.OPTION_CLOSEST_SYNC
)
retriever.release()
}
}