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

Simplify AudioHelper. #3011

Merged
merged 1 commit into from
Feb 10, 2023
Merged
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
40 changes: 10 additions & 30 deletions app/src/main/java/com/github/libretube/helpers/AudioHelper.kt
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,22 @@ package com.github.libretube.helpers

import android.content.Context
import android.media.AudioManager
import android.os.Build
import androidx.core.content.getSystemService
import androidx.core.math.MathUtils
import androidx.media.AudioManagerCompat
import com.github.libretube.extensions.normalize

class AudioHelper(
context: Context,
private val stream: Int = AudioManager.STREAM_MUSIC
) {

private lateinit var audioManager: AudioManager
private var minimumVolumeIndex = 0
private var maximumVolumeIndex = 16

init {
(context.getSystemService(Context.AUDIO_SERVICE) as? AudioManager)?.let {
audioManager = it
maximumVolumeIndex = it.getStreamMaxVolume(stream)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
minimumVolumeIndex = it.getStreamMinVolume(stream)
}
}
}
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
get() {
return if (this::audioManager.isInitialized) {
audioManager.getStreamVolume(stream) - minimumVolumeIndex
} else {
0
}
}
get() = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) - minimumVolumeIndex
set(value) {
if (this::audioManager.isInitialized) {
val vol = MathUtils.clamp(value, minimumVolumeIndex, maximumVolumeIndex)
audioManager.setStreamVolume(stream, vol, 0)
}
val vol = MathUtils.clamp(value, minimumVolumeIndex, maximumVolumeIndex)
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, vol, 0)
}

fun setVolumeWithScale(value: Int, maxValue: Int, minValue: Int = 0) {
Expand Down