直播到VideoView

时间:2018-02-03 19:30:58

标签: java android streaming android-videoview

我正在尝试创建一个接收jpeg文件流(来自python服务器)的应用程序,并将它们“直播”到应用程序中的VideoView小部件供用户查看。但我很难接收输入并将其发送到视频视图。 任何帮助,将不胜感激, 感谢。

1 个答案:

答案 0 :(得分:1)

对于直播,您可以使用Exo Player

<强>用法:

向你的gradle添加bellow依赖:

compile 'com.google.android.exoplayer:exoplayer:r2.5.+'

将以下行添加到您要显示视频的xml文件中。

<com.google.android.exoplayer2.ui.SimpleExoPlayerView
    android:id="@+id/exo_player"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:resize_mode="fill"/>

这是你的活动:

//I have used butterknife you can bind view as per your convinience
@BindView(R.id.exo_player)
SimpleExoPlayerView feedVideo;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);  
    setUpVideo();
}
private void setUpVideo() {
    // 1. Create a default TrackSelector
    BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
    TrackSelection.Factory videoTrackSelectionFactory =
            new AdaptiveTrackSelection.Factory(bandwidthMeter);
    trackSelector = new 
    DefaultTrackSelector(videoTrackSelectionFactory);

    // 2. Create the player
    player = ExoPlayerFactory.newSimpleInstance(this, 
             trackSelector);

    feedVideo.setPlayer(player);
    setUpVideoData();
}

private void setUpVideoData() {
    // 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, "yourApplicationName"), bandwidthMeter);
    // Produces Extractor instances for parsing the media data.
    ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
    // This is the MediaSource representing the media to be played.
    MediaSource videoSource = new ExtractorMediaSource(Uri.parse(urlToPlay),
            dataSourceFactory, extractorsFactory, null, null);
    // Prepare the player with the source.
    player.prepare(videoSource);

    // Auto Play video as soon as it buffers
    player.setPlayWhenReady(true);
}

@Override
public void onPause() {
    super.onPause();
    pauseLivePreview();
}

@Override
public void onResume() {
    super.onResume();
    resumeLivePreview();
}

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

private void pauseLivePreview() {
    if (player != null) {
    if (feedVideo != null && feedVideo.getPlayer() != null) {
        feedVideo.getPlayer().release();
    }
}