Skip to content

Instantly share code, notes, and snippets.

@Qw4z1
Created July 13, 2024 07:20
Show Gist options
  • Save Qw4z1/61afb34168f9ac9f29bf0af6ec77ee5e to your computer and use it in GitHub Desktop.
Save Qw4z1/61afb34168f9ac9f29bf0af6ec77ee5e to your computer and use it in GitHub Desktop.
Simple animated audio waveform meant to place in a player. RowScope is specific to my current use case to import the correct weight function.
@Composable
fun RowScope.WaveForm(progress: List<Float>) {
// State to track the horizontal offset for the animation
var offsetState by remember { mutableStateOf(0f) }
val itemWidth = with(LocalDensity.current) { 4.dp.toPx() }
val padding = with(LocalDensity.current) { 1.dp.toPx() }
// Animate the offset change
val animatedOffset by animateFloatAsState(
targetValue = offsetState,
animationSpec = tween(
durationMillis = 100, // Make the animation duration short
easing = LinearEasing // Use linear easing for a consistent animation speed
)
)
// Update the offset when the progress list changes size
LaunchedEffect(progress.size) {
offsetState = padding + itemWidth
}
Box(
modifier = Modifier
.weight(1f)
.height(40.dp)
.clip(RoundedCornerShape(0.dp))
.drawBehind {
drawOffset(progress, itemWidth, animatedOffset)
}
)
}
private fun DrawScope.drawOffset(
progress: List<Float>,
itemWidth: Float,
animatedOffset: Float
) {
val itemMaxHeight = size.height * 0.7f
progress.reversed()
.forEachIndexed { index, item ->
val left = size.width - animatedOffset * (index)
val top = size.height - (itemMaxHeight * item)
drawRect(
color = Color(0xFFC8CDF2),
topLeft = Offset(left, top),
size = Size(itemWidth, itemMaxHeight * item)
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment