LibreTube/app/src/main/java/com/github/libretube/helpers/AudioHelper.kt

31 lines
1.2 KiB
Kotlin
Raw Normal View History

package com.github.libretube.helpers
import android.content.Context
import android.media.AudioManager
2023-02-10 04:52:31 +05:30
import androidx.core.content.getSystemService
import androidx.core.math.MathUtils
2023-02-10 04:52:31 +05:30
import androidx.media.AudioManagerCompat
import com.github.libretube.extensions.normalize
2023-02-10 04:52:31 +05:30
class AudioHelper(context: Context) {
private val audioManager = context.getSystemService<AudioManager>()!!
private val minimumVolumeIndex = AudioManagerCompat
.getStreamMinVolume(audioManager, AudioManager.STREAM_MUSIC)
private val maximumVolumeIndex = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
var volume: Int
2023-02-10 04:52:31 +05:30
get() = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) - minimumVolumeIndex
set(value) {
2023-02-10 04:52:31 +05:30
val vol = MathUtils.clamp(value, minimumVolumeIndex, maximumVolumeIndex)
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, vol, 0)
}
fun setVolumeWithScale(value: Int, maxValue: Int, minValue: Int = 0) {
volume = value.normalize(minValue, maxValue, minimumVolumeIndex, maximumVolumeIndex)
}
fun getVolumeWithScale(maxValue: Int, minValue: Int = 0): Int {
return volume.normalize(minimumVolumeIndex, maximumVolumeIndex, minValue, maxValue)
}
}