Skip to content

Commit

Permalink
Revert "Better audio normalization"
Browse files Browse the repository at this point in the history
This reverts commit c0ad7dc.
  • Loading branch information
z-huang committed Oct 29, 2024
1 parent afb3268 commit c5b2856
Showing 1 changed file with 10 additions and 24 deletions.
34 changes: 10 additions & 24 deletions app/src/main/java/com/zionhuang/music/playback/MusicService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import android.content.Context
import android.content.Intent
import android.database.SQLException
import android.media.audiofx.AudioEffect
import android.media.audiofx.LoudnessEnhancer
import android.net.ConnectivityManager
import android.os.Binder
import androidx.core.content.getSystemService
Expand Down Expand Up @@ -135,6 +134,8 @@ import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.time.LocalDateTime
import javax.inject.Inject
import kotlin.math.min
import kotlin.math.pow
import kotlin.time.Duration.Companion.seconds


Expand Down Expand Up @@ -170,10 +171,9 @@ class MusicService : MediaLibraryService(),
database.format(mediaMetadata?.id)
}

private val normalizeFactor = MutableStateFlow(1f)
val playerVolume = MutableStateFlow(dataStore.get(PlayerVolumeKey, 1f).coerceIn(0f, 1f))

private var loudnessEnhancer: LoudnessEnhancer? = null

lateinit var sleepTimer: SleepTimer

@Inject
Expand Down Expand Up @@ -243,7 +243,9 @@ class MusicService : MediaLibraryService(),

connectivityManager = getSystemService()!!

playerVolume.collectLatest(scope) {
combine(playerVolume, normalizeFactor) { playerVolume, normalizeFactor ->
playerVolume * normalizeFactor
}.collectLatest(scope) {
player.volume = it
}

Expand Down Expand Up @@ -296,25 +298,10 @@ class MusicService : MediaLibraryService(),
) { format, normalizeAudio ->
format to normalizeAudio
}.collectLatest(scope) { (format, normalizeAudio) ->
runCatching {
if (!normalizeAudio) {
loudnessEnhancer?.enabled = false
loudnessEnhancer?.release()
loudnessEnhancer = null
} else {
if (loudnessEnhancer == null) {
loudnessEnhancer = LoudnessEnhancer(player.audioSessionId)
}
fun Float?.toMb() = ((this ?: 0f) * 100).toInt()

var loudnessMb = format?.loudnessDb?.toFloat().toMb()
if (loudnessMb !in -2000..2000) {
// Extreme loudness value detected, turning off normalization for this song
loudnessMb = 0
}
loudnessEnhancer?.setTargetGain(5f.toMb() - loudnessMb)
loudnessEnhancer?.enabled = true
}
normalizeFactor.value = if (normalizeAudio && format?.loudnessDb != null) {
min(10f.pow(-format.loudnessDb.toFloat() / 20), 1f)
} else {
1f
}
}

Expand Down Expand Up @@ -789,7 +776,6 @@ class MusicService : MediaLibraryService(),
player.removeListener(this)
player.removeListener(sleepTimer)
player.release()
loudnessEnhancer?.release()
super.onDestroy()
}

Expand Down

0 comments on commit c5b2856

Please sign in to comment.