Android Studio 在Exo播放器中播放字节数组

2guxujil  于 12个月前  发布在  Android
关注(0)|答案(1)|浏览(193)

我正在尝试用exo播放器播放字节数组,有什么建议吗?

private fun playAudio(bytes: ByteArray) {
    lifecycleScope.launch {
        
        player!!.apply {
            setMediaSource(createMediaSource(bytes))
            prepare()
            playWhenReady = true // start playing when the exoplayer has setup
            
        }
    }
}

fun createMediaSource(bytes: ByteArray): MediaSource {
    val byteArrayDataSource = ByteArrayDataSource(bytes)
    val factory = DataSource.Factory {
        return@Factory byteArrayDataSource
    }
    return ProgressiveMediaSource.Factory(factory,
        ExtractorsFactory { return@ExtractorsFactory arrayOf(Mp3Extractor()) })
        .createMediaSource(
            MediaItem.fromUri(
                Uri.EMPTY
            )
        )
}

字符串

这也是我的录音函数,它有一个返回byteString/byteArray的函数

suspend fun recordVoice(audioRecord: AudioRecord?) = withContext(Dispatchers.IO) {
    Log.i("LOG", "BUFFER SIZE: $BUFFER_SIZE_RECORDING")
    audioRecord?.startRecording()
    val buf = ByteArray(BUFFER_SIZE_RECORDING)
    try {
        do {
            val byteRead = audioRecord?.read(buf, 0, buf.size) ?: break

            if (byteRead < -1)
                break
            onRecordedByteString.byteString(buf.toByteString(0, byteRead))
        } while (true)
    } catch (e: Exception) {
        e.printStackTrace()
    }
}


和缓冲

companion object {
    private const val RECORDER_SAMPLE_RATE = 44100
    private const val RECORDER_CHANNELS: Int = AudioFormat.CHANNEL_IN_STEREO
    private const val RECORDER_AUDIO_ENCODING: Int = AudioFormat.ENCODING_PCM_16BIT
    private val BUFFER_SIZE_RECORDING = AudioRecord.getMinBufferSize(
        RECORDER_SAMPLE_RATE,
        RECORDER_CHANNELS,
        RECORDER_AUDIO_ENCODING
    ) * 4

}


在录制并按下播放按钮后,此问题发生x1c 0d1x

ux6nzvsh

ux6nzvsh1#

创建临时文件更安全、更容易

val tempWav = File.createTempFile("tempAudio", "wav")
      tempWav.deleteOnExit()
      val fos = FileOutputStream(tempMp3)
      fos.write(byte)
      fos.close()

      var mediaItem = MediaItem.fromUri(tempWav.toURI().toString())

字符串

相关问题