ExoPlayer is simple to use

Keywords: Mobile Android Google github network

I. Introduction

ExoPlayer is an application-level media player project of google Open Source, which includes ExoPlayer library and demo, github address: https://github.com/google/ExoPlayer.

Two. Overview

The core of the ExoPlayer library is the ExoPlayer interface. ExoPlayer exposes the functions of traditional high-level media players, such as media buffering, playback, pause and fast-forward. Instead of loading and rendering media files directly, ExoPlayer delegates these tasks to components injected when creating a player or when the player is ready to play. All common components implemented by ExoPlayer are:

  • Media Source: A media resource that defines the media to be played, loads the media, and where to load the media. Simply put, Media Source is the media file that we want to play. It can be a local resource or a network resource. MediaSource is injected through ExoPlayer.prepare method at the beginning of playback.
  • Renderer: Renderer for rendering media files. Renderers are injected when the player is created.
  • Track Selector: Track Selector, which is used to select tracks provided by MediaSource for each available renderer.
  • LoadControl: Used to control when and how much media resources are buffered by Media Source. LoadControl is injected when the player is created.

Three, use

1. Adding dependencies

implementation 'com.google.android.exoplayer:exoplayer:2.X.X'

This approach relies on the entire ExoPlayer library. We can also rely on libraries that we really need. For example, if you want to play ordinary media resources, you can rely only on Core and UI libraries.

implementation 'com.google.android.exoplayer:exoplayer-core:2.X.X'
implementation 'com.google.android.exoplayer:exoplayer-ui:2.X.X'

The entire ExoPlayer library consists of five sublibraries. Depending on the entire ExoPlayer library is equivalent to relying on five sublibraries.

  • exoplayer-core: Core Functions (Necessary)
  • exoplayer-dash: supporting DASH content
  • exoplayer-hls: supporting HLS content
  • exoplayer-smoothstreaming: SmoothStreaming content support
  • exoplayer-ui: UI components and related resources for ExoPlayer.

2. Add PlayerView to Layout File

<com.google.android.exoplayer2.ui.PlayerView
    android:id="@+id/exo_play_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
private PlayerView mPlayerView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    [...]
    mPlayerView = findViewById(R.id.exo_play_view);
}

3. Create an instance of SimpleExoPlayer

SimpleExoPlayer is a default generic implementation of the ExoPlayer interface.

// Get the appropriate bandwidth by default
BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
// Create tracked factories
TrackSelection.Factory factory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
// Create trackers
DefaultTrackSelector trackSelection = new DefaultTrackSelector(factory);

// Create a Player
SimpleExoPlayer exoPlayer = ExoPlayerFactory.newSimpleInstance(context, trackSelection);

// The second way is to pass in the Default Renderers Factory, Default Track Selector and Default Load Control, and then return the player instance.
//SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(
//         new DefaultRenderersFactory(context),
//         new DefaultTrackSelector(), 
//         new DefaultLoadControl());

4. Prepare and start playing

// Generate a data media instance through which media data can be loaded
DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, "exoplayerdemo"));
// Create resources
Uri uri = Uri.parse(url);
MediaSource mediaSources = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
// Attach the player to view
mPlayerView.setPlayer(exoPlayer);
// Ready to play
exoPlayer.prepare(mediaSource);
// When ready, play automatically. If ready, call this method to implement pause and start function.
exoPlayer.setPlayWhenReady(true);

5. Release Player

if (null != exoPlayer) {
    exoPlayer.stop();
    exoPlayer.release();
    exoPlayer = null;
}

6. Combination of media resources

The ExoPlayer library provides Concatenating Media Source and Dynamic Concatenating Media Source that can be used to seamlessly merge and play multiple media resources.

Using Concatenating Media Source
The following method builds a composite media file.

/**
 * list Is a collection of resource addresses, which can be audio, video, etc.
 */
private MediaSource getMediaSource(ArrayList<String> list) {
    DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, "exoplayerdemo"));
    // Assemble URL s into resource classes
    MediaSource[] mediaSources = new MediaSource[list.size()];
    for (int i = 0; i < list.size(); i++) {
        Uri uri = Uri.parse(list.get(i));
        mediaSources[i] = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
    }
    MediaSource mediaSource = mediaSources.length == 1 ? mediaSources[0] : new ConcatenatingMediaSource(mediaSources);
    return mediaSource;
}

7. Recycling Play

The ExoPlayer library provides Looping Media Source for circular playback.

// Single resource loop playback specifies the number of loopCount loops
MediaSource source = new ExtractorMediaSource.Factory(dataSourceFactory).createMediaSource(uri);
MediaSource mediaSource = new LoopingMediaSource(source, loopCount);

// Loop playback of multiple resources
MediaSource source = new ConcatenatingMediaSource(mediaSources);
MediaSource mediaSource = new LoopingMediaSource(source, loopCount);

8. Monitoring ExoPlayer Events

// Adding event listeners
exoPlayer.addListener(listener);
// Remove event monitoring
exoPlayer.removeListener(listener);

private Player.DefaultEventListener listener = new Player.DefaultEventListener() {
    @Override
    public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
        // Video playback status
        L.d("playbackState = " + playbackState + " playWhenReady = " + playWhenReady);
        switch (playbackState){
            case Player.STATE_IDLE:
                // free
                break;
            case Player.STATE_BUFFERING:
                // Buffer
                break;
            case Player.STATE_READY:
                // Get ready
                break;
            case Player.STATE_ENDED:
                // End
                break;
            default:
                break;
        }
    }

    @Override
    public void onPlayerError(ExoPlaybackException error) {
        // Report errors
        switch (error.type){
            case ExoPlaybackException.TYPE_SOURCE:
                // Error loading resources
                break;
            case ExoPlaybackException.TYPE_RENDERER:
                // Errors in rendering
                break;
            case ExoPlaybackException.TYPE_UNEXPECTED:
                // unexpected error
                break;
        }
    }
};

9. Custom Interface

If not, ExoPlayer defaults to using a playback control interface that is PlayerControlView If you don't want to use this control interface at all, you can modify it in the layout file.

<com.google.android.exoplayer2.ui.PlayerView
   [...]
   app:use_controller="false"/>

In this way, the control interface is not displayed.

Customize the behavior of Player Control View

<com.google.android.exoplayer2.ui.PlayerView
   android:id="@+id/video_view"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   app:show_timeout="10000"
   app:fastforward_increment="30000"
   app:rewind_increment="30000"/>

In the example above, both fast forward and fast backward have been changed to 30 seconds. The automatic disappearance time of the control interface is 10 seconds.

Customize the appearance of the Player Control View interface

You can customize the control interface and then change the property controller_layout_id in the layout file.

<com.google.android.exoplayer2.ui.PlayerView  
   android:id="@+id/video_view"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   app:controller_layout_id="@layout/custom_playback_control"/>
PlayerControlView identifies all UI elements it uses through ID. When you customize layout files, you must keep the ID of standard elements, such as @id/exo_play or @id/exo_pause, so that PlayerControlView has a chance to find them.

The default control interface for PlayerControlView is R.layout.exo_playback_control_view.xml. You can also copy it directly from the ExoPlayer library to the res directory of app and make changes accordingly.

Four, ending

The basic playback is almost complete. ExoPlayer also has many advanced functions, such as

1. Resource Shearing Clipping Media Source
2. Speed multiplier
3, subtitles
4. Playing Streaming Media
And so on.

No research has been done yet. Interested partners can go and see it.

Posted by DrTom on Tue, 23 Apr 2019 18:03:35 -0700