首页 > 解决方案 > 在 ExoPlayer 中播放加密视频文件时遇到问题,超过几秒钟

问题描述

我正在尝试通过 ExoPlayer 播放我在我的应用程序中加密的视频文件,但只要我尝试播放视频超过几秒钟,视频就不会播放。

我正在使用“AES/GCM/NoPadding”加密对媒体进行加密。

下面是我使用 Exoplayer 播放加密流的自定义 DataSource 类:

class EncryptedDataSource(
    private val context: Context,
    private val datasource: DataSource,
    private val secureKey: String
) : DataSource {

    private var cipherInputStream: CipherInputStream? = null

    private var uri: Uri? = null

    override fun addTransferListener(transferListener: TransferListener?) {}

    override fun open(dataSpec: DataSpec?): Long {
        uri = dataSpec?.uri

        val encryptedFile = File(context.filesDir, secureKey)
        val inputStream = encryptedFile.inputStream()
        val cipher = EncryptUtils.getCipherForEncryptedStream(secureKey)
        cipherInputStream = CipherInputStream(inputStream, cipher)
        
        return C.LENGTH_UNSET.toLong()
    }

    override fun read(buffer: ByteArray?, offset: Int, readLength: Int): Int {
        Assertions.checkNotNull<Any>(cipherInputStream)

        val bytesRead = cipherInputStream?.read(buffer, offset, readLength) ?: 0

        return if (bytesRead < 0) {
            C.RESULT_END_OF_INPUT
        } else {
            bytesRead
        }
    }

    override fun getUri(): Uri? = uri

    @Throws(IOException::class)
    override fun close() {
        if (cipherInputStream != null) {
            cipherInputStream?.close()
            cipherInputStream = null
            datasource.close()
        }
    }
}

当我播放 2/3 秒长的视频时,一切正常并且视频播放。如果视频不再播放,我会陷入调用 open() 函数的循环,然后是 read() 函数几次,然后是 close() 函数。然后 open() 函数被立即调用,并继续循环。

有人对我哪里出错有任何建议吗?我知道加密/解密逻辑可以正常工作,因为我已经测试过在 ExoPlayer 之外加密和解密视频就好了,而且我知道 2/3 秒的短视频可以正常工作。

标签: androidencryptionexoplayer

解决方案


感谢以下博客:

http://blog.moagrius.com/android/android-play-encrypted-video-in-exoplayer/

我能够解决我的问题。


推荐阅读