Use try-catch where appropriate

This commit is contained in:
Fabian Wiesel
2024-03-01 18:32:33 +01:00
parent 282753854f
commit ea8357bb3c

View File

@@ -33,6 +33,7 @@ import android.util.Log
import android.widget.Toast
import androidx.core.app.NotificationCompat
import androidx.core.app.ServiceCompat
import java.io.IOException
import java.io.InputStream
import java.net.Socket
@@ -134,16 +135,13 @@ class ListenService : Service() {
private fun doListen(address: String?, port: Int) {
val lt = Thread {
Socket(address, port).use { socket ->
val result = runCatching { socket.getInputStream() }
if (result.isSuccess) {
result.getOrNull()?.let {inputStream ->
try {
val inputStream = socket.getInputStream()
withAudioTrack { audioTrack ->
streamAudio(inputStream, audioTrack)
}
}
}
else {
val exception = result.exceptionOrNull()
catch (exception : IOException) {
Log.e(TAG, "Failed to stream audio", exception)
}
}
@@ -168,25 +166,24 @@ class ListenService : Service() {
audioEncoding,
bufferSize,
AudioTrack.MODE_STREAM)
val playback = runCatching { audioTrack.play() }
if (playback.isFailure) {
Log.e(TAG, "Failed to start output due to ", playback.exceptionOrNull())
return
try {
audioTrack.play()
block(audioTrack)
}
runCatching { block(audioTrack) }
catch (e : java.lang.IllegalStateException ) {
Log.e(TAG, "Failed to start output due to ", e)
}
finally {
audioTrack.stop()
}
}
private fun streamAudio(inputStream: InputStream, audioTrack: AudioTrack) {
val readBuffer = ByteArray(byteBufferSize)
val decodedBuffer = ShortArray(byteBufferSize * 2)
try {
while (!Thread.currentThread().isInterrupted) {
val read = runCatching { inputStream.read(readBuffer) }
if (read.isFailure) {
return
}
val len = read.getOrDefault(-1)
val len = inputStream.read(readBuffer)
if (len < 0) {
return
}
@@ -199,6 +196,9 @@ class ListenService : Service() {
updateCallback?.invoke()
}
}
} catch (e: IOException) {
Log.e(TAG, "Failed to read from socket due to ")
}
}
private fun playAlert() {