davidliu
Committed by GitHub

State checking and synchronization for the communication workaround audiotrack (#383)

@@ -25,6 +25,7 @@ import android.os.Build @@ -25,6 +25,7 @@ import android.os.Build
25 import androidx.annotation.RequiresApi 25 import androidx.annotation.RequiresApi
26 import io.livekit.android.dagger.InjectionNames 26 import io.livekit.android.dagger.InjectionNames
27 import io.livekit.android.util.CloseableCoroutineScope 27 import io.livekit.android.util.CloseableCoroutineScope
  28 +import io.livekit.android.util.LKLog
28 import kotlinx.coroutines.MainCoroutineDispatcher 29 import kotlinx.coroutines.MainCoroutineDispatcher
29 import kotlinx.coroutines.flow.MutableStateFlow 30 import kotlinx.coroutines.flow.MutableStateFlow
30 import kotlinx.coroutines.flow.collectLatest 31 import kotlinx.coroutines.flow.collectLatest
@@ -122,8 +123,11 @@ constructor( @@ -122,8 +123,11 @@ constructor(
122 123
123 stop() 124 stop()
124 125
125 - audioTrack?.stop()  
126 - audioTrack?.release() 126 + audioTrack?.let { track ->
  127 + synchronized(track) {
  128 + track.release()
  129 + }
  130 + }
127 } 131 }
128 132
129 private fun onStateChanged(started: Boolean, playoutStopped: Boolean) { 133 private fun onStateChanged(started: Boolean, playoutStopped: Boolean) {
@@ -170,7 +174,13 @@ constructor( @@ -170,7 +174,13 @@ constructor(
170 } 174 }
171 175
172 val audioTrack = audioTrack ?: buildAudioTrack().also { audioTrack = it } 176 val audioTrack = audioTrack ?: buildAudioTrack().also { audioTrack = it }
173 - audioTrack.play() 177 + synchronized(audioTrack) {
  178 + if (audioTrack.state == AudioTrack.STATE_INITIALIZED) {
  179 + audioTrack.play()
  180 + } else {
  181 + LKLog.i { "Attempted to start communication workaround but track was not initialized." }
  182 + }
  183 + }
174 } 184 }
175 185
176 private fun pauseAudioTrackIfNeeded() { 186 private fun pauseAudioTrackIfNeeded() {
@@ -180,7 +190,15 @@ constructor( @@ -180,7 +190,15 @@ constructor(
180 return 190 return
181 } 191 }
182 192
183 - audioTrack?.pause() 193 + audioTrack?.let { track ->
  194 + synchronized(track) {
  195 + if (track.state == AudioTrack.STATE_INITIALIZED) {
  196 + track.pause()
  197 + } else {
  198 + LKLog.d { "Attempted to stop communication workaround but track was not initialized." }
  199 + }
  200 + }
  201 + }
184 } 202 }
185 203
186 // Reference from Android code, AudioFormat.getBytesPerSample. BitPerSample / 8 204 // Reference from Android code, AudioFormat.getBytesPerSample. BitPerSample / 8