Java doesn’t support .mp3 format, so I tried to use JLayer library to play mp3 audio. But the Player of JLayer doesn’t support play-time volume control and pause.
So I’m finding a better way to play mp3 audio on Desktop, with Compose Multiplatform.
The input mp3 audio will be given as a ByteArray. It should support these features.
- pause and play
- play-time volume control
- conditional audio loop
expect class AudioManager constructor(data: ByteArray) {
var volume: Float
var loop: Boolean
fun play()
fun pause()
fun stop()
}
This is the expect class of my AudioManager.
actual class AudioManager actual constructor(data: ByteArray) {
private val mediaPlayer = MediaPlayer().apply {
val mediaSource = ByteArrayMediaDataSource(data)
setDataSource(mediaSource)
prepare()
}
actual var volume: Float = 1F
set(value) {
mediaPlayer.setVolume(value, value)
field = value
}
actual var loop: Boolean = false
set(value) {
mediaPlayer.isLooping = value
field = value
}
actual fun play() {
mediaPlayer.start()
}
actual fun pause() {
mediaPlayer.pause()
}
actual fun stop() {
mediaPlayer.stop()
}
inner class ByteArrayMediaDataSource(private val data: ByteArray) : MediaDataSource() {
override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int {
System.arraycopy(data, position.toInt(), buffer, offset, size)
return size
}
override fun getSize(): Long {
return data.size.toLong()
}
override fun close() { }
}
}
And this is sample code for Android target using MediaPlayer that I’ve written.