Skip to content

Instantly share code, notes, and snippets.

@scruffyfox
Last active February 1, 2023 12:57
Show Gist options
  • Save scruffyfox/885cfbe77327d248a7e67f53b16bf079 to your computer and use it in GitHub Desktop.
Save scruffyfox/885cfbe77327d248a7e67f53b16bf079 to your computer and use it in GitHub Desktop.
Playing a video from Assets using ExoPlayer 2
/**
* It took me AGES to figure this out, seriously, exoplayer documentation IS SO BAD.
*/
package xxx
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.cube.arc.R
import com.cube.lib.util.bind
import com.google.android.exoplayer2.ExoPlayerFactory
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory
import com.google.android.exoplayer2.source.ExtractorMediaSource
import com.google.android.exoplayer2.trackselection.AdaptiveTrackSelection
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector
import com.google.android.exoplayer2.ui.SimpleExoPlayerView
import com.google.android.exoplayer2.upstream.AssetDataSource
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DataSource.Factory
class VideoPlayerActivity : AppCompatActivity()
{
lateinit var player: SimpleExoPlayer
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.video_player_view)
val videoPlayer = findViewById(R.id.video_player) as SimpleExoPlayerView
val videoTrackSelectionFactory = AdaptiveTrackSelection.Factory(null)
val trackSelector = DefaultTrackSelector(videoTrackSelectionFactory)
player = ExoPlayerFactory.newSimpleInstance(this, trackSelector)
videoPlayer.requestFocus()
videoPlayer.useController = true
videoPlayer.player = player
val dataSourceFactory: DataSource.Factory = object : Factory
{
override fun createDataSource(): DataSource
{
return AssetDataSource(this@VideoPlayerActivity)
}
}
val videoSource = ExtractorMediaSource(Uri.parse("assets:///onboarding_video.mp4"), dataSourceFactory, DefaultExtractorsFactory(), null, null)
player.prepare(videoSource)
player.playWhenReady = true
}
override fun onDestroy()
{
super.onDestroy()
player.release()
}
}
@pandelisgreen13
Copy link

Since this is the first result on Google for "ExoPlayer play local asset" I thought I share a slightly simpler way of playing local assets (thanks to andrewlewis@).

ExoPlayer 2.12 introduces the MediaItem class so you can do:

val firstVideoUri = Uri.parse("asset:///localfile.mp3")
val firstItem = MediaItem.fromUri(firstVideoUri)
player.addMediaItem(firstItem)

Note that the URI should start with asset:/// not assets:///

thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment