From c5b2856126927b65ae2d264c1f6a0e712a84c703 Mon Sep 17 00:00:00 2001 From: Zion Huang Date: Tue, 29 Oct 2024 09:01:57 +0800 Subject: [PATCH] Revert "Better audio normalization" This reverts commit c0ad7dcca80904fddf94d1b70c99d66339a7c0a8. --- .../zionhuang/music/playback/MusicService.kt | 34 ++++++------------- 1 file changed, 10 insertions(+), 24 deletions(-) diff --git a/app/src/main/java/com/zionhuang/music/playback/MusicService.kt b/app/src/main/java/com/zionhuang/music/playback/MusicService.kt index 378f74a8a..dbae89d14 100644 --- a/app/src/main/java/com/zionhuang/music/playback/MusicService.kt +++ b/app/src/main/java/com/zionhuang/music/playback/MusicService.kt @@ -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 @@ -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 @@ -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 @@ -243,7 +243,9 @@ class MusicService : MediaLibraryService(), connectivityManager = getSystemService()!! - playerVolume.collectLatest(scope) { + combine(playerVolume, normalizeFactor) { playerVolume, normalizeFactor -> + playerVolume * normalizeFactor + }.collectLatest(scope) { player.volume = it } @@ -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 } } @@ -789,7 +776,6 @@ class MusicService : MediaLibraryService(), player.removeListener(this) player.removeListener(sleepTimer) player.release() - loudnessEnhancer?.release() super.onDestroy() }