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

问题描述 投票:0回答:1

我正在尝试使用 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

}

录制并按下播放按钮后会发生此问题

java android android-studio kotlin exoplayer
1个回答
0
投票

创建临时文件更安全、更简单

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

      var mediaItem = MediaItem.fromUri(tempWav.toURI().toString())
© www.soinside.com 2019 - 2024. All rights reserved.