Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: volume fade in/out #91

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -103,15 +103,16 @@ class MainActivity : ComponentActivity() {
position = position,
duration = duration,
isLive = isLive,
onPrevious = { player.previous() },
onNext = { player.next() },
onPrevious = { player.simpleFadeDemo { player.previous() } },
onNext = { player.simpleFadeDemo { player.next() } },
isPaused = state.value != AudioPlayerState.PLAYING,
onTopBarAction = { showSheet = true },
onPlayPause = {
if (player.playerState == AudioPlayerState.PLAYING) {
player.pause()
player.fadeVolume(0f, callback = { player.pause() })
} else {
player.play()
player.fadeVolume()
}
},
onSeek = { player.seek(it, TimeUnit.MILLISECONDS) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,10 @@ import com.google.android.exoplayer2.upstream.RawResourceDataSource
import com.google.android.exoplayer2.upstream.cache.CacheDataSource
import com.google.android.exoplayer2.upstream.cache.SimpleCache
import com.google.android.exoplayer2.util.Util
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import timber.log.Timber
import java.util.Locale
Expand Down Expand Up @@ -150,6 +153,34 @@ abstract class BaseAudioPlayer internal constructor(
exoPlayer.volume = value * volumeMultiplier
}

/**
* fade volume of the current exoPlayer by a simple linear function.
*/
fun fadeVolume(volume: Float = 1f, duration: Long = 500, interval: Long = 20L, callback: () -> Unit = { }): Deferred<Unit> {
return scope.async {
val volumeDiff = (volume - exoPlayer.volume) * interval / duration
var fadeInDuration = duration
while (fadeInDuration > 0) {
fadeInDuration -= interval
exoPlayer.volume += volumeDiff
delay(interval)
}
exoPlayer.volume = volume
callback()
return@async
}
}

/**
* a simple fade in/out wrapper. for KA-example only, do not use.
*/
fun simpleFadeDemo(callback: () -> Unit = { }) {
fadeVolume(0f, callback={
callback()
fadeVolume()
})
}

var playbackSpeed: Float
get() = exoPlayer.playbackParameters.speed
set(value) {
Expand Down