-
Notifications
You must be signed in to change notification settings - Fork 226
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor: extract player volume fade out into a new class
- Loading branch information
Showing
3 changed files
with
59 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
46 changes: 46 additions & 0 deletions
46
...src/main/java/au/com/shiftyjelly/pocketcasts/repositories/playback/PlayerVolumeFadeOut.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
package au.com.shiftyjelly.pocketcasts.repositories.playback | ||
|
||
import kotlin.math.exp | ||
import kotlinx.coroutines.CoroutineScope | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.delay | ||
import kotlinx.coroutines.launch | ||
|
||
class PlayerVolumeFadeOut( | ||
private var player: Player, | ||
private val scope: CoroutineScope, | ||
) { | ||
companion object { | ||
private const val VOLUME_CHANGES_PER_SECOND = 30.0 | ||
private const val FADE_VELOCITY = 2.0 | ||
private const val FROM_VOLUME = 1.0 | ||
private const val TO_VOLUME = 0.0 | ||
} | ||
|
||
fun performFadeOut(duration: Double, onStopPlaying: () -> Unit) { | ||
val totalSteps = (duration * VOLUME_CHANGES_PER_SECOND).toInt() | ||
val delayBetweenSteps = (1000 / VOLUME_CHANGES_PER_SECOND).toLong() | ||
|
||
var currentStep = 0 | ||
|
||
scope.launch(Dispatchers.Main) { | ||
while (currentStep < totalSteps) { | ||
val normalizedTime = (currentStep.toDouble() / totalSteps).coerceIn(0.0, 1.0) | ||
val volumeMultiplier = exp(-FADE_VELOCITY * normalizedTime) * (1 - normalizedTime) | ||
val newVolume = TO_VOLUME + (FROM_VOLUME - TO_VOLUME) * volumeMultiplier | ||
|
||
if (player.isPlaying()) { | ||
player.setVolume(newVolume.toFloat()) | ||
} else { | ||
onStopPlaying() | ||
break | ||
} | ||
|
||
currentStep++ | ||
delay(delayBetweenSteps) | ||
} | ||
|
||
player.setVolume(TO_VOLUME.toFloat()) | ||
} | ||
} | ||
} |