Vitor Ferreira
Vitor Ferreira

Reputation: 1095

How to play a video on exoplayer from a content uri?

In my app the user can select some videos from the gallery to edit them. After the user selects videos, I create a list of Uri and I want to play in exoplayer. I can play videos using their file path such as /storage/emulated/0/Android/data/com.vitor.videoeditor/files/Movies/VideoEditor/VID_20200722_133503.mp4, but I don't know how to do the same with a uri like content: // media / external / file / 305166.I tried to pass the uri directly to DataSpec () but it didn't work. What is the correct way to play the videos?

private fun playVideos(pathsList: List<String>) {
    val concatenatingMediaSource = ConcatenatingMediaSource()
    pathsList.forEach { filePath ->
        val dataSpec = DataSpec(Uri.fromFile(File(filePath)))
        val fileDataSource = FileDataSource()
        try {
            fileDataSource.open(dataSpec)
        } catch (e: FileDataSource.FileDataSourceException) {
            e.printStackTrace()
        }
        val dataSourceFactory = DataSource.Factory { fileDataSource }
        val mediaSource: MediaSource = ProgressiveMediaSource.Factory(dataSourceFactory)
                .createMediaSource(Uri.fromFile(File(filePath)))
        concatenatingMediaSource.addMediaSource(mediaSource)
    }

    simpleExoPlayer = ExoPlayerFactory.newSimpleInstance(applicationContext)

    with(simpleExoPlayer) {
        prepare(concatenatingMediaSource)
        playerView.player = simpleExoPlayer
        playWhenReady = true
        repeatMode = Player.REPEAT_MODE_ALL
    }
}

Upvotes: 3

Views: 1445

Answers (1)

Vikas Acharya
Vikas Acharya

Reputation: 4152

content uri will expires soon So only during the file opening by intent you can play a video then it will expire. to avoid that

val cr = applicationContext.contentResolver
val flg: Int = Intent.FLAG_GRANT_WRITE_URI_PERMISSION or 
               Intent.FLAG_GRANT_READ_URI_PERMISSION                 
cr.takePersistableUriPermission(uri!!, flg)

put above code in onActivity result. So that the uri will not expire.

and use same content uri later on.

Upvotes: 1

Related Questions