If you target API 23 and above, create a class like this
class MyMediaDataSource(val data: ByteArray) : MediaDataSource() {
override fun readAt(position: Long, buffer: ByteArray, offset: Int, size: Int): Int {
if (position >= data.size) return -1 // -1 indicates EOF
val endPosition: Int = (position + size).toInt()
var size2: Int = size
if (endPosition > data.size)
size2 -= endPosition - data.size
System.arraycopy(data, position.toInt(), buffer, offset, size2)
return size2
}
override fun getSize(): Long {
return data.size.toLong()
}
override fun close() {}
}
and use like this
val mediaSource = MyMediaDataSource(byteArray)
MediaPlayer().apply {
setAudioStreamType(AudioManager.STREAM_MUSIC)
setDataSource(mediaSource)
setOnCompletionListener { release() }
prepareAsync()
setOnPreparedListener { start() }
}
credits to krishnakumarp's answer above and to this article