Skip to content

Commit

Permalink
refactor: AudioMediaRecorder to improve readability and resource mana…
Browse files Browse the repository at this point in the history
…gement
  • Loading branch information
kl3jvi authored Nov 7, 2024
1 parent 1e10eb8 commit 36a60c4
Showing 1 changed file with 8 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import okio.buffer
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.ByteOrder
import javax.inject.Inject
Expand Down Expand Up @@ -151,7 +152,7 @@ class AudioMediaRecorder @Inject constructor(
dataSizeBuffer.order(ByteOrder.LITTLE_ENDIAN)
dataSizeBuffer.putInt(dataSize)

java.io.RandomAccessFile(file, "rw").use { randomAccessFile ->
RandomAccessFile(file, "rw").use { randomAccessFile ->
// Update Chunk Size
randomAccessFile.seek(CHUNK_SIZE_OFFSET.toLong())
randomAccessFile.write(chunkSizeBuffer.array())
Expand Down Expand Up @@ -216,6 +217,7 @@ class AudioMediaRecorder @Inject constructor(
suspend fun convertWavToMp4(inputFilePath: String): Boolean = withContext(Dispatchers.IO) {
var codec: MediaCodec? = null
var muxer: MediaMuxer? = null
var success = true

try {
FileInputStream(File(inputFilePath)).use { fileInputStream ->
Expand Down Expand Up @@ -318,17 +320,16 @@ class AudioMediaRecorder @Inject constructor(
}
if (retryCount >= MAX_RETRY_COUNT) {
appLogger.e("Reached maximum retries without receiving output from codec.")
return@withContext false
success = false
}
}
} ?: run {
appLogger.e("[RecordAudio] convertWavToMp4: mp4OutputPath is null")
return@withContext false
success = false
}
}
} catch (e: Exception) {
appLogger.e("Could not convert wav to mp4: ${e.message}", throwable = e)
return@withContext false
} finally {
try {
muxer?.let { safeMuxer ->
Expand All @@ -337,7 +338,7 @@ class AudioMediaRecorder @Inject constructor(
}
} catch (e: Exception) {
appLogger.e("Could not stop or release MediaMuxer: ${e.message}", throwable = e)
return@withContext false
success = false
}

try {
Expand All @@ -347,10 +348,10 @@ class AudioMediaRecorder @Inject constructor(
}
} catch (e: Exception) {
appLogger.e("Could not stop or release MediaCodec: ${e.message}", throwable = e)
return@withContext false
success = false
}
}
return@withContext true
success
}

companion object {
Expand Down

0 comments on commit 36a60c4

Please sign in to comment.