How to use android exoplayer
Asked Answered
R

8

43

I am looking to implement Google's ExoPlayer in my app. Their documentation seems pretty vague to me, and all I am looking for is to play a video from an URL, no complicated custom settings or anything like that. Haven't found any tutorials on how to do it. The example they have on git is way too complicated for what I need and, since I am new to video streaming, I did not understand much. All I have managed to do so far is to display a com.google.android.exoplayer.AspectRatioFrameLayout.

Basically, I have an URL. I need to play the video, and handle onConfigurationChanged when the user flips the screen.

Can anyone help?

Ruelas answered 28/9, 2015 at 11:5 Comment(6)
Searching for exoplayer tutorial on a major search engine turns up davekb.com/… and youtube.com/watch?v=6VjF638VObA. The ExoPlayer developers recommend reviewing their demo app.Shahjahanpur
I reviewed their demo app, and I did not understand anything. As I said, I am new to video streaming. I also looked over davekb's example, and the FrameworkSampleSource class is not only deprecated, but I do not have the same constructor he seems to have. He has FrameworkSampleSource(mContext, uri, /* headers */ null, numRenderers), and I have a constructor without the number of renderersRuelas
OK, just making sure that you tried what's out there. I haven't played with ExoPlayer yet (though it's actually on my short list), and I don't get the sense that it is aimed at simple scenarios.Shahjahanpur
I just have to customize the looks. I understand that the classic way does not offer a way to do this, but the exoplayer does. Hopefully, someone will post an exampleRuelas
I'm creating a library that will allow you to do this. stay tunned ;)Chaldea
so here it is : github.com/HugoGresse/SimpleExoPlayer It's missing a lot of stuff including FullscreenActivity, the documentation, but you can start using VideoPlayerFactory and use the project as a git submodule for the moment, I will push it on jCenter once finishChaldea
I
26

The ExoMedia library wraps exoplayer in simpler api and provides a video view for use in layouts. See usage examples on github: https://github.com/brianwernick/ExoMedia/

Indusium answered 20/11, 2015 at 7:58 Comment(6)
I can confirm that I successfully used this lib in my project to replace VideoView, and it works great.Enki
This library is easy to use but shows videos slightly tilted. github.com/brianwernick/ExoMedia/issues/318Poleax
also this library doesn't support seamless looping as it should be, so if you need this feature you should try something else!Pharisee
Even though ExoMedia wrapper makes using exoplayer a lot easier it's a nightmare if you plan on resizing your videos dynamically and attaching or detaching your player since it doesnt handle surface resizing and doing it manually ends up releasing the surfaceviewInvolucel
Just to make sure that no one is misguided; seamless looping has only really been supported by the ExoPlayer since V2 (there were still gaps in V1) which ExoMedia has a task to update to. As far as resizing goes, that bug was fixed a while ago.Bartholemy
This library is buggy! I won't recommend it!Endurance
N
7

Exoplayer is a very advanced library. Even writing a bare minimum would take 40-50 lines of code. So if you really wanna use a sword to chop onions, here is a direct copy pasta :

//manifest.xml 

<manifest ...>
  <uses-permission android:name="android.permission.INTERNET"/>
  <application
    android:usesCleartextTraffic="true"
    ...>

    ...

  </application>
</manifest>
//app/build.gradle
apply plugin: 'com.android.application'

android {
    ...
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
}

dependencies {
    ...
    implementation 'com.google.android.exoplayer:exoplayer:2.10.4'
}



    protected void onCreate(Bundle savedInstanceState) {
        ...

        Context ctx =this;
        String CONTENT_URL = "https://www.radiantmediaplayer.com/media/bbb-360p.mp4";
        int playerID=R.id.pv_main;
        int appNameStringRes = R.string.app_name;
        startPlayingVideo(this,CONTENT_URL,playerID,appNameStringRes);


    }

    //
    private void startPlayingVideo(Context ctx , String CONTENT_URL, int playerID, String appNameRes) {

        PlayerView pvMain = ctx.findViewById(playerID);

        //BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        //TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);        
        //TrackSelector trackSelectorDef = new DefaultTrackSelector(videoTrackSelectionFactory);
        TrackSelector trackSelectorDef = new DefaultTrackSelector();

        SimpleExoPlayer absPlayerInternal = ExoPlayerFactory.newSimpleInstance(ctx, trackSelectorDef);

        String userAgent = Util.getUserAgent(ctx, ctx.getString(appNameRes));

        DefaultDataSourceFactory defdataSourceFactory = new DefaultDataSourceFactory(ctx,userAgent);
        Uri uriOfContentUrl = Uri.parse(CONTENT_URL);
        MediaSource mediaSource = new ProgressiveMediaSource.Factory(defdataSourceFactory).createMediaSource(uriOfContentUrl);

        absPlayerInternal.prepare(mediaSource);
        absPlayerInternal.setPlayWhenReady(true);

        pvMain.setPlayer(absPlayerInternal);

    }

    private void stopPlayer(PlayerView pv,SimpleExoPlayer absPlayer){
        pv.setPlayer(null);
        absPlayer.release();
        absPlayer = null;
    }

simply add the player view in your activity layout, call the startPlayingVideo(...) in onCreate() and stopPlayer() in the onStop() . I am not an expert but i can try explaining this if you want, but you asked for no complicated stuff, so here is just the code

Nf answered 18/9, 2019 at 11:6 Comment(0)
D
2

A VideoView would be a better idea in case you wish to display only a Video URL. ExoPlayer requires some developmental effort, even for invoking its simple instance. However, there is an advantage of faster and more efficient playback, backed up by an active open-source community. This link provides a good walk through the implementation giving ample reasons to switch to ExoPlayer. Ofcourse, do checkout the official developer guide, the updated version has split modules for simpler implementation.

Diffuser answered 11/5, 2017 at 10:40 Comment(0)
B
2
//Add dependency in manifest file 
    implementation 'com.google.android.exoplayer:exoplayer:2.7.3'


// Add exoplayer in your layout(xml) file 
 <RelativeLayout
        android:id="@+id/rl_video"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <com.google.android.exoplayer2.ui.PlayerView
        android:id="@+id/videoFullScreenPlayer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#A6000000"
        app:controller_layout_id="@layout/exo_playback_control_view"
        app:player_layout_id="@layout/exo_simple_player_view"
        app:repeat_toggle_modes="none"
        app:show_timeout="45000"
        app:surface_type="texture_view"
        />
        <ProgressBar
            android:id="@+id/spinnerVideoDetails"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginBottom="8dp"
            android:indeterminate="true"/>
    </RelativeLayout>




// open video with below code

// initialise varible 
 PlayerView videoFullScreenPlayer;
    SimpleExoPlayer player;
    ProgressBar spinnerVideoDetails;


// find Id 
 videoFullScreenPlayer = findViewById(R.id.videoFullScreenPlayer);
        spinnerVideoDetails = findViewById(R.id.spinnerVideoDetails);

// open video method 
private void setUp() {
        initializePlayer();
        if (videoUrl == null) {
            return;
        }
        buildMediaSource(Uri.parse(videoUrl ));
    }
    private void initializePlayer() {
        if (player == null) {

            BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
            TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
            TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
            // 1. Create a default TrackSelector
            DefaultLoadControl loadControl = new DefaultLoadControl.Builder().setBufferDurationsMs(32*1024, 64*1024, 1024, 1024).createDefaultLoadControl();
            // 2. Create the player
            player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);
            videoFullScreenPlayer.setPlayer(player);
        }
    }

    private void buildMediaSource(Uri mUri) {
        // Measures bandwidth during playback. Can be null if not required.
        DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        // Produces DataSource instances through which media data is loaded.
        DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this,
                Util.getUserAgent(this, getString(R.string.app_name)), bandwidthMeter);
        // This is the MediaSource representing the media to be played.
        MediaSource videoSource = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(mUri);
        // Prepare the player with the source.
        player.prepare(videoSource);
        player.setPlayWhenReady(true);
        player.addListener(this);
    }

    private void releasePlayer() {
        if (player != null) {
            player.release();
            player = null;
        }
    }

    private void pausePlayer() {
        if (player != null) {
            player.setPlayWhenReady(false);
            player.getPlaybackState();
        }
    }

    private void resumePlayer() {
        if (player != null) {
            player.setPlayWhenReady(true);
            player.getPlaybackState();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        pausePlayer();
       /* if (mRunnable != null) {
            mHandler.removeCallbacks(mRunnable);
        }*/
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        resumePlayer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releasePlayer();
    }

    @Override
    public void onTimelineChanged(Timeline timeline, Object manifest, int reason) {
    }

    @Override
    public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {
    }

    @Override
    public void onLoadingChanged(boolean isLoading) {
    }

    @Override
    public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
        switch (playbackState) {
            case Player.STATE_BUFFERING:
                spinnerVideoDetails.setVisibility(View.VISIBLE);
                break;
            case Player.STATE_ENDED:
                // Activate the force enable
                break;
            case Player.STATE_IDLE:
                break;
            case Player.STATE_READY:
                spinnerVideoDetails.setVisibility(View.GONE);
                break;
            default:
                // status = PlaybackStatus.IDLE;
                break;
        }
    }

    @Override
    public void onRepeatModeChanged(int repeatMode) {
    }

    @Override
    public void onShuffleModeEnabledChanged(boolean shuffleModeEnabled) {
    }

    @Override
    public void onPlayerError(ExoPlaybackException error) {
    }

    @Override
    public void onPositionDiscontinuity(int reason) {
    }

    @Override
    public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {
    }

    @Override
    public void onSeekProcessed() {
    }
Bruell answered 28/2, 2020 at 12:25 Comment(0)
H
0

Here is a new Github Library named MagicalExoPlayer, That based on ExoPlayer.

Supports MP4, HLS and Dash.

Supports custom Aspect Ratios

Support FullScreen

Heredes answered 3/7, 2019 at 14:20 Comment(1)
The full-screen feature doesn't work in Kotlin. Heads up for Kotlin developersDisrepute
Z
0

This is how you can use ExoPlayer in android studio project using JAVA

Implement the latest version (as of now) of ExoPlayer dependency

implementation 'com.google.android.exoplayer:exoplayer:2.18.2'

first the PlayerView in the xml code in your_activity.xml file

<com.google.android.exoplayer2.ui.StyledPlayerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/styled_player_view"
            app:resize_mode="fit"
            app:show_timeout="0"
            app:use_artwork="true"
            app:use_controller="true"

            app:surface_type="texture_view"/>


Now the JAVA code

Declare the variables

StyledPlayerView styledPlayerView;
ExoPlayer player;

Now the method

private void playVideo(){
        String videoPath = "your/path/to/the/media";           //storage location of the video to be played
        Uri videoUri = Uri.parse(videoPath);                   //converting it to Uri
        MediaItem mediaItem = MediaItem.fromUri(videoUri);     //build the MediaItem

        player = new ExoPlayer.Builder(this).build();                //this is the latest version of player. SimpleExoPlayer has been deprecated
        styledPlayerView = findViewById(R.id.styled_player_view);   //video will be played inside this view which is in the xml file
        styledPlayerView.setPlayer(player);                         //binding the PlayerView to the Player

        player.setMediaItem(mediaItem);   //now Player knows which Media to play

        player.prepare();               //getting ready for play
        player.play();                  //now is the time to play



    }//end playVideo()

Now free the Player when you close the activity

@Override
    protected void onDestroy() {
        super.onDestroy();
        
        styledPlayerView.setPlayer(null);
        player.release();

    }//end onDestroy()

Stil don't get it? Visit
https://exoplayer.dev/hello-world.html

Zaidazailer answered 12/2, 2023 at 17:35 Comment(0)
O
0

The latest version of Exoplayer as of today 08-Mar-2023 is implementation 'com.google.android.exoplayer:exoplayer:2.18.4'

Orelle answered 8/3, 2023 at 21:45 Comment(0)
G
0

i know it late, but hope this help, i have implemented exo with kotlin:

simply you need to add the dependencies to your gradle. its different based on the version you want to use. im using exoPlayer2

to create your exoPlayer instance :

val exoPlayer = ExoPlayerFactory.newSimpleInstance(
        context,
        DefaultTrackSelector(),
        DefaultLoadControl()
    )

after you have created your exoPlayer instance, you neet to load the media source to your exoPlayer and play it.

to create media source from your url :

    val source = ExtractorMediaSource(
        Uri.parse(streamUrl),
        DefaultDataSourceFactory(
            context,
            Util.getUserAgent(context, "exoplayerexample")
        ), DefaultExtractorsFactory(), null, null
    )

and to play it with your exoPlayer:

exoPlayer.prepare(source)
exoPlayer.playWhenReady = true

and for showing it on the UI, you can use com.google.android.exoplayer2.ui.PlayerView and simply set the exoPlayer to UI with:

playerView.player = exoPlayer
Gordy answered 26/8, 2023 at 14:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.