Android Studio Mediaplayer how to fade in and out

前端 未结 3 2181
慢半拍i
慢半拍i 2021-02-20 17:08

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).

3条回答
  •  甜味超标
    2021-02-20 17:37

    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)
    }
    

提交回复
热议问题