You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio(Kotlin)访问res/raw预录视频路径失败求助

问题原因
  • 你用MediaStore.Images.Media.DATA查询raw资源的Uri完全不匹配:MediaStore只索引设备媒体库中的文件,而raw目录下的资源是打包在APK里的,不属于媒体库范畴,所以query返回的cursor为空,自然拿不到路径。
  • raw资源没有真实的文件系统路径,它是APK的一部分,无法直接通过Uri获取到文件路径字符串。
解决方案

方案1:直接使用资源输入流(推荐)

如果你的SlowTask可以修改为接受InputStream而非文件路径,这是最直接高效的方式:

修改按钮点击事件代码:

heartRateButton.setOnClickListener {
    val inputStream = resources.openRawResource(R.raw.heartratevideo)
    // 调整SlowTask使其支持InputStream参数
    val slowTask = SlowTask { heartRate ->
        showToast(heartRate)
    }
    slowTask.execute(inputStream)
}

同时修改SlowTask的参数类型,从String改为InputStream,在任务内部直接读取输入流处理视频即可。

方案2:将raw资源复制到本地存储获取路径

如果必须依赖文件路径,只能把APK里的raw资源复制到内部/外部存储,再获取路径:

先添加复制资源的工具函数:

fun copyRawResourceToFile(context: Context, resId: Int, fileName: String): String? {
    val outputFile = File(context.filesDir, fileName)
    // 避免重复复制
    if (outputFile.exists()) {
        return outputFile.absolutePath
    }
    return try {
        context.resources.openRawResource(resId).use { inputStream ->
            FileOutputStream(outputFile).use { outputStream ->
                val buffer = ByteArray(1024)
                var length: Int
                while (inputStream.read(buffer).also { length = it } > 0) {
                    outputStream.write(buffer, 0, length)
                }
            }
        }
        outputFile.absolutePath
    } catch (e: IOException) {
        e.printStackTrace()
        null
    }
}

再修改按钮点击事件代码:

heartRateButton.setOnClickListener {
    val videoPath = copyRawResourceToFile(this, R.raw.heartratevideo, "heartratevideo.mp4")
    if (videoPath != null) {
        val slowTask = SlowTask { heartRate ->
            showToast(heartRate)
        }
        slowTask.execute(videoPath)
    } else {
        Log.e("VideoPath", "Failed to copy raw resource to file")
    }
}

补充说明

  • android.resource://类型的Uri指向APK内部资源,不属于文件系统文件,ContentResolver.query无法通过MediaStore字段获取路径,因为MediaStore根本没索引这些资源。
  • 就算是处理媒体库中的视频,也应该用MediaStore.Video.Media.DATA而非MediaStore.Images.Media.DATA,但这依然不适用于raw资源。

内容的提问来源于stack exchange,提问作者Sarfraz Nawaz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 09:12:19