微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法在 Android 11 中将文件路径传递给 MediaRecorder

如何解决无法在 Android 11 中将文件路径传递给 MediaRecorder

我将文件路径传递给 MediaRecorder 以创建视频文件

File(filePath).exists() 返回假, 但 MediaRecorder 因 IOException 而失败, java.io.FileNotFoundException:/storage/emulated/0/DCIM/XXX/XXX0001.mp4:打开失败:EEXIST(文件存在)

我尝试通过 getContentResolver().insert() 创建 Uri,但它也给出了 UNIQUE 约束失败:files._data (code 2067 sqlITE_CONSTRAINT_UNIQUE[2067])

问题不在于我从未测试过我的应用程序的新手机。如果我从文件管理器中删除视频,问题就会开始。

解决方法

创建一个临时文件并复制临时文件中的全部内容。

/**
  * Create a temp file with the specified format.
  * Usage: Image from gallery,Copy file to app directory before upload
  */
@SuppressLint("SimpleDateFormat")
    suspend fun createTempFile(fileType: BaseMediaFragment.FileType,extension: String): File? =
        withContext(Dispatchers.IO) {
            val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
            val storageDir: File? =
                getApplication<Application>().applicationContext?.getExternalFilesDir(fileType.tempFileDirectory)

            if (!storageDir?.exists().isTrue())
                storageDir?.mkdirs()

            return@withContext File.createTempFile(
                "${fileType.tempFilePrefix}_${timeStamp}_",/* prefix */
                extension,/* suffix */
                storageDir /* directory */
            )
        }

    /**
     * Copy the specified input stream to the output file.
     */
    private suspend fun copyStreamToFile(inputStream: InputStream,outputFile: File) {
        withContext(Dispatchers.IO) {
            inputStream.use { input ->
                val outputStream = FileOutputStream(outputFile)
                outputStream.use { output ->
                    val buffer = ByteArray(4 * 1024) // buffer size
                    while (true) {
                        val byteCount = input.read(buffer)
                        if (byteCount < 0) break
                        output.write(buffer,byteCount)
                    }
                    output.flush()
                }
            }
        }
    ```

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。