1616 * along with this program. If not, see <https://www.gnu.org/licenses/>.
1717 */
1818
19-
2019package me.kavishdevar.aln.utils
2120
2221import android.media.AudioManager
@@ -31,6 +30,7 @@ object MediaController {
3130 private lateinit var audioManager: AudioManager
3231 var iPausedTheMedia = false
3332 var userPlayedTheMedia = false
33+ private val handler = Handler (Looper .getMainLooper())
3434
3535 fun initialize (audioManager : AudioManager ) {
3636 this .audioManager = audioManager
@@ -43,7 +43,7 @@ object MediaController {
4343 Log .d(" MediaController" , " Playback config changed, iPausedTheMedia: $iPausedTheMedia " )
4444 if (configs != null && ! iPausedTheMedia) {
4545 Log .d(" MediaController" , " Seems like the user changed the state of media themselves, now I won't `play` until the ear detection pauses it." )
46- Handler ( Looper .getMainLooper()) .postDelayed({
46+ handler .postDelayed({
4747 iPausedTheMedia = ! audioManager.isMusicActive
4848 userPlayedTheMedia = audioManager.isMusicActive
4949 }, 7 ) // i have no idea why, but android sends a pause event a hundred times after the user does something.
@@ -99,21 +99,34 @@ object MediaController {
9999 if (initialVolume == null ) {
100100 initialVolume = audioManager.getStreamVolume(AudioManager .STREAM_MUSIC )
101101 Log .d(" MediaController" , " Initial Volume Set: $initialVolume " )
102- audioManager.setStreamVolume(
103- AudioManager .STREAM_MUSIC ,
104- audioManager.getStreamMaxVolume(AudioManager .STREAM_MUSIC ) * 1 / 12 , 0
105- )
102+ val targetVolume = audioManager.getStreamMaxVolume(AudioManager .STREAM_MUSIC ) * 1 / 12
103+ smoothVolumeTransition(initialVolume!! , targetVolume)
106104 }
107105 Log .d(" MediaController" , " Initial Volume: $initialVolume " )
108106 }
109107
110108 @Synchronized
111109 fun stopSpeaking () {
112110 Log .d(" MediaController" , " Stopping speaking, initialVolume: $initialVolume " )
113- initialVolume?. let { volume ->
114- audioManager.setStreamVolume (AudioManager .STREAM_MUSIC , volume, 0 )
115- initialVolume = null // Reset to null after restoring the volume
111+ if ( initialVolume != null ) {
112+ smoothVolumeTransition( audioManager.getStreamVolume (AudioManager .STREAM_MUSIC ), initialVolume !! )
113+ initialVolume = null
116114 }
117115 }
118116
117+ private fun smoothVolumeTransition (fromVolume : Int , toVolume : Int ) {
118+ val step = if (fromVolume < toVolume) 1 else - 1
119+ val delay = 50L // 50 milliseconds delay between each step
120+ var currentVolume = fromVolume
121+
122+ handler.post(object : Runnable {
123+ override fun run () {
124+ if (currentVolume != toVolume) {
125+ currentVolume + = step
126+ audioManager.setStreamVolume(AudioManager .STREAM_MUSIC , currentVolume, 0 )
127+ handler.postDelayed(this , delay)
128+ }
129+ }
130+ })
131+ }
119132}
0 commit comments