如何使用安卓exoplayer

问题描述 投票:0回答:8

我希望在我的应用程序中实现 Google 的

ExoPlayer
。他们的文档对我来说似乎相当模糊,我所寻找的只是从 URL 播放视频,没有复杂的自定义设置或类似的东西。尚未找到任何有关如何操作的教程。他们在 git 上提供的示例对于我的需要来说太复杂了,而且由于我是视频流新手,所以我不太了解。到目前为止我所能做的就是显示一个
com.google.android.exoplayer.AspectRatioFrameLayout

基本上,我有一个网址。我需要播放视频,并在用户翻转屏幕时处理

onConfigurationChanged

有人可以帮忙吗?

android video-streaming exoplayer
8个回答
26
投票

ExoMedia 库将 exoplayer 包装在更简单的 api 中,并提供在布局中使用的视频视图。请参阅 github 上的使用示例:https://github.com/brianwernick/ExoMedia/


7
投票

Exoplayer 是一个非常先进的库。即使编写最少的代码也需要 40-50 行代码。所以如果你真的想用剑来切洋葱,这里有一个直接复制的意大利面:

//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;
    }

只需在您的活动布局中添加

player view
,在
startPlayingVideo(...)
中调用
onCreate()
,在
stopPlayer()
中调用
onStop()
。我不是专家,但如果您愿意,我可以尝试解释这一点,但您没有要求复杂的东西,所以这只是代码


2
投票

如果您只想显示视频 URL,VideoView 会是一个更好的主意。 ExoPlayer 需要一些开发工作,即使是调用其简单实例。然而,它的优点是播放速度更快、效率更高,并且有活跃的开源社区的支持。 此链接提供了一个很好的实施过程,为切换到 ExoPlayer 提供了充分的理由。 当然,请查看官方开发者指南,更新版本已拆分模块以简化实现。


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() {
    }

0
投票

这里有一个新的 Github 库,名为 MagicalExoPlayer,基于 ExoPlayer。

支持MP4HLSDash

支持自定义长宽比

支持全屏


0
投票

这就是如何使用JAVA在android studio项目中使用ExoPlayer

实现 ExoPlayer 依赖项的最新版本(截至目前)

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

首先是your_activity.xml文件中xml代码中的PlayerView

<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"/>


现在是JAVA代码

声明变量

StyledPlayerView styledPlayerView;
ExoPlayer player;

现在是方法

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()

现在,当您关闭活动时释放播放器

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

    }//end onDestroy()

还是不明白?参观
https://exoplayer.dev/hello-world.html


0
投票

截至今天 2023 年 3 月 8 日的 Exoplayer 最新版本是 实现 'com.google.android.exoplayer:exoplayer:2.18.4'


0
投票

我知道晚了,但希望这会有所帮助:

您只需将依赖项添加到您的 gradle 中即可。 根据您要使用的版本而有所不同。我正在使用 exoPlayer2

创建您的 exoPlayer 实例:

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

创建 exoPlayer 实例后,您需要将媒体源加载到 exoPlayer 并播放它。

从您的网址创建媒体源:

    val source = ExtractorMediaSource(
        Uri.parse(streamUrl),
        PlayerBaseFragment.CacheDataSourceFactory(
            ApplicationLoader.applicationActivity,
            maxCacheSize,
            maxFileSize
        ), DefaultExtractorsFactory(), null, null
    )

并用你的 exoPlayer 来播放它:

exoPlayer.prepare(source)
exoPlayer.playWhenReady = true

要在 UI 上显示它,您可以使用

com.google.android.exoplayer2.ui.PlayerView
并简单地将 exoPlayer 设置为 UI:

playerView.player = exoPlayer
© www.soinside.com 2019 - 2024. All rights reserved.