如何使用exoplayer自动播放视频

如何使用exoplayer自动播放视频

本文介绍了如何使用exoplayer自动播放视频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在com.google.android.exoplayer2.ui.SimpleExoPlayerView视图中加载了视频,但我想使其在视图加载时自动开始.现在,用户必须单击播放"按钮.

I have a video loaded in a com.google.android.exoplayer2.ui.SimpleExoPlayerView view but I want to make it automatically start when the view loads. Right now, the user has to click the play button.

推荐答案

SimpleExoPlayer与SurfaceView配合良好,有一些方法可以设置播放器的表面.

SimpleExoPlayer works well with a SurfaceView, there are methods to set the surface of the player.

这是我创建SimpleExoPlayer的方式:

This is how I create the SimpleExoPlayer:

/** Create a default TrackSelector **/
TrackSelector trackSelector = new DefaultTrackSelector(new Handler());

/** Create a default LoadControl **/
LoadControl loadControl = new DefaultLoadControl();

/** Create the player **/
mPlayer = ExoPlayerFactory.newSimpleInstance(context, trackSelector, loadControl);

/** Make the ExoPlayer play when its data source is prepared **/
mPlayer.setPlayWhenReady(true);

我拥有这些工厂,因此不必在每次设置新数据源时都创建它们.

I hold these factories so I don't have to create them each time I set a new data source.

/** Produces Extractor instances for parsing the media data **/
mExtractorsFactory = new DefaultExtractorsFactory();

/** Produces DataSource instances through which media data is loaded **/
mDataSourceFactory = new DefaultDataSourceFactory(
        context, Util.getUserAgent(context, "AppName")
);

我使用以下方法在播放器上设置新的数据源.此方法使用之前创建的工厂.

I use the following method to set a new data source on the player. This method uses the factories created earlier.

对我来说,String source是设备SD卡上保存的MP4文件的URI.早先setPlayWhenReady(true),此视频准备就绪后,&准备播放,它将立即开始.

For me, the String source is a URI to an MP4 file held on the device's SD card. Having setPlayWhenReady(true) earlier, once this video is prepared & ready to play it will begin immediately.

public void setDataSource(SurfaceView view, String source) {
    stopMedia();
    mPlayer.setVideoSurfaceView(view);
    view.requestFocus();

    // Create the media source
    mVideoSource = new ExtractorMediaSource(Uri.fromFile(
            new File(source)),
            mDataSourceFactory, mExtractorsFactory, null, null);

    // Prepare the player with the source.
    mPlayer.prepare(mVideoSource);
}

这篇关于如何使用exoplayer自动播放视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 02:28