I am working with the mediaplayer class in android studio. I simply want to fade out one sound and fade in the other sound instead of using setVolume(0,0) and setVolume(1,1). >
There's a VolumeShaper class added in API Level 26 (https://developer.android.com/guide/topics/media/volumeshaper). Here's an example of volume out and in, you can shape the fade in or out speed (ramp) adding more points to times and volumes arrays. Time points must start at 0 and end at 1 and they are relative times of volume ramping.
fun fadeOutConfig(duration: Long): VolumeShaper.Configuration {
val times = floatArrayOf(0f, 1f) // can add more points, volume points must correspond to time points
val volumes = floatArrayOf(1f, 0f)
return VolumeShaper.Configuration.Builder()
.setDuration(duration)
.setCurve(times, volumes)
.setInterpolatorType(VolumeShaper.Configuration.INTERPOLATOR_TYPE_CUBIC)
.build()
}
fun fadeInConfig(duration: Long): VolumeShaper.Configuration {
val times = floatArrayOf(0f, 1f) // can add more points, volume points must correspond to time points
val volumes = floatArrayOf(0f, 1f)
return VolumeShaper.Configuration.Builder()
.setDuration(duration)
.setCurve(times, volumes)
.setInterpolatorType(VolumeShaper.Configuration.INTERPOLATOR_TYPE_CUBIC)
.build()
}
fun fadeInOrOutAudio(mediaPlayer: MediaPlayer, duration: Long, out: Boolean) {
val config = if (out) fadeOutConfig(duration) else fadeInConfig(duration)
val volumeShaper = mediaPlayer.createVolumeShaper(config)
volumeShaper.apply(VolumeShaper.Operation.PLAY)
}