Wrap java exceptions in runCatching blocks

This commit is contained in:
Fabian Wiesel
2024-02-26 20:42:45 +01:00
parent c6c60d9dbd
commit 41506bc601

View File

@@ -33,7 +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
class ListenService : Service() {
@@ -136,11 +136,19 @@ class ListenService : Service() {
private var updateCallback: (() -> Unit)? = null
private fun doListen(address: String?, port: Int) {
val lt = Thread {
try {
val socket = Socket(address, port)
streamAudio(socket)
} catch (e: IOException) {
Log.e(TAG, "Failed to stream audio", e)
Socket(address, port).use { socket ->
val result = runCatching { socket.getInputStream() }
if (result.isSuccess) {
result.getOrNull()?.let {inputStream ->
withAudioTrack { audioTrack ->
streamAudio(inputStream, audioTrack)
}
}
}
else {
val exception = result.exceptionOrNull()
Log.e(TAG, "Failed to stream audio", exception)
}
}
if (!Thread.currentThread().isInterrupted) {
// If this thread has not been interrupted, likely something
@@ -155,8 +163,7 @@ class ListenService : Service() {
lt.start()
}
@Throws(IllegalArgumentException::class, IllegalStateException::class, IOException::class)
private fun streamAudio(socket: Socket) {
private fun withAudioTrack(block: (AudioTrack) -> Unit): Unit {
Log.i(TAG, "Setting up stream")
val audioTrack = AudioTrack(AudioManager.STREAM_MUSIC,
frequency,
@@ -164,15 +171,29 @@ class ListenService : Service() {
audioEncoding,
bufferSize,
AudioTrack.MODE_STREAM)
val inputStream = socket.getInputStream()
var read = 0
audioTrack.play()
try {
val playback = runCatching { audioTrack.play() }
if (playback.isFailure) {
Log.e(TAG, "Failed to start output due to ", playback.exceptionOrNull())
return
}
runCatching { block(audioTrack) }
audioTrack.stop()
}
private fun streamAudio(inputStream: InputStream, audioTrack: AudioTrack) {
val readBuffer = ByteArray(byteBufferSize)
val decodedBuffer = ShortArray(byteBufferSize * 2)
while (socket.isConnected && read != -1 && !Thread.currentThread().isInterrupted) {
read = inputStream.read(readBuffer)
val decoded: Int = AudioCodecDefines.CODEC.decode(decodedBuffer, readBuffer, read, 0)
while (!Thread.currentThread().isInterrupted) {
val read = runCatching { inputStream.read(readBuffer) }
if (read.isFailure) {
return
}
val len = read.getOrDefault(-1)
if (len < 0) {
return
}
val decoded: Int = AudioCodecDefines.CODEC.decode(decodedBuffer, readBuffer, len, 0)
if (decoded > 0) {
audioTrack.write(decodedBuffer, 0, decoded)
val decodedBytes = ShortArray(decoded)
@@ -181,12 +202,6 @@ class ListenService : Service() {
updateCallback?.invoke()
}
}
} catch (e: Exception) {
Log.e(TAG, "Connection failed", e)
} finally {
audioTrack.stop()
socket.close()
}
}
private fun playAlert() {