Добавление медиа-контроллера в ExoPlayer в Android

Я использую exoplayer для воспроизведения потокового видео через URL, а учебник содержит 2 кнопки для воспроизведения и приостановки видео через потоковую передачу. Я изменил это на автоматическое воспроизведение при запуске приложения, но я не знаю, как добавить обычное мультимедиа Контроллер со всеми необходимыми функциями в этом коде для просмотра медиа-контроллеров как любого приложения медиаплеера.

Мой код:

public class mainactivity extends AppCompatActivity implements ManifestFetcher.ManifestCallback<HlsPlaylist>,
    ExoPlayer.Listener,HlsSampleSource.EventListener, AudioManager.OnAudioFocusChangeListener {

private SurfaceView surface;
private ExoPlayer player;
private PlayerControl playerControl;
private String video_url;
private Handler mainHandler;
private AudioManager am;
private String userAgent;
private ManifestFetcher<HlsPlaylist> playlistFetcher;
private static final int BUFFER_SEGMENT_SIZE = 64 * 1024;
private static final int MAIN_BUFFER_SEGMENTS = 254;
public static final int TYPE_VIDEO = 0;
private TrackRenderer videoRenderer;
private MediaCodecAudioTrackRenderer audioRenderer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_mainactivity);
    surface = (SurfaceView) findViewById(R.id.surface_view); // we import surface

    player = ExoPlayer.Factory.newInstance(2);
    playerControl = new PlayerControl(player); // we init player
    video_url = "urlhere.m3u8" +
            ""; //video url
    am = (AudioManager) this.getApplicationContext().getSystemService(Context.AUDIO_SERVICE); // for requesting audio
    mainHandler = new Handler(); //handler required for hls
    userAgent = Util.getUserAgent(this, "MainActivity"); //useragent required for hls
    HlsPlaylistParser parser = new HlsPlaylistParser(); // init HlsPlaylistParser
    playlistFetcher = new ManifestFetcher<>(video_url, new DefaultUriDataSource(this, userAgent),
            parser); // url goes here, useragent and parser
    playlistFetcher.singleLoad(mainHandler.getLooper(), this); //with 'this' we'll implement ManifestFetcher.ManifestCallback<HlsPlaylist>
    //listener with it will come two functions
}
//inside onSingleManifest we'll code to play hls
@Override
public void onSingleManifest(HlsPlaylist manifest) {
    LoadControl loadControl = new DefaultLoadControl(new DefaultAllocator(BUFFER_SEGMENT_SIZE));
    DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
    PtsTimestampAdjusterProvider timestampAdjusterProvider = new PtsTimestampAdjusterProvider();
    boolean haveSubtitles = false;
    boolean haveAudios = false;
    if (manifest instanceof HlsMasterPlaylist) {
        HlsMasterPlaylist masterPlaylist = (HlsMasterPlaylist) manifest;
        haveSubtitles = !masterPlaylist.subtitles.isEmpty();

    }
    // Build the video/id3 renderers.
    DataSource dataSource = new DefaultUriDataSource(this, bandwidthMeter, userAgent);
    HlsChunkSource chunkSource = new HlsChunkSource(true /* isMaster */, dataSource, manifest,
            DefaultHlsTrackSelector.newDefaultInstance(this), bandwidthMeter,
            timestampAdjusterProvider, HlsChunkSource.ADAPTIVE_MODE_SPLICE);
    HlsSampleSource sampleSource = new HlsSampleSource(chunkSource, loadControl,
            MAIN_BUFFER_SEGMENTS * BUFFER_SEGMENT_SIZE, mainHandler, this, TYPE_VIDEO);
    MediaCodecVideoTrackRenderer videoRenderer = new MediaCodecVideoTrackRenderer(this, sampleSource,
            MediaCodecSelector.DEFAULT, MediaCodec.VIDEO_SCALING_MODE_SCALE_TO_FIT);
    MediaCodecAudioTrackRenderer audioRenderer = new MediaCodecAudioTrackRenderer(sampleSource,
            MediaCodecSelector.DEFAULT);
    this.videoRenderer = videoRenderer;
    this.audioRenderer = audioRenderer;
    pushSurface(false); // here we pushsurface
    player.prepare(videoRenderer,audioRenderer); //prepare
    player.addListener(this); //add listener for the text field
    if (requestFocus())
        player.setPlayWhenReady(true);
}
public boolean requestFocus() {
    return AudioManager.AUDIOFOCUS_REQUEST_GRANTED ==
            am.requestAudioFocus(mainactivity.this, AudioManager.STREAM_MUSIC,
                    AudioManager.AUDIOFOCUS_GAIN);
}
private void pushSurface(boolean blockForSurfacePush) {
    if (videoRenderer == null) {return;}
    if (blockForSurfacePush) {
        player.blockingSendMessage(
                videoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, surface.getHolder().getSurface());
    } else {
        player.sendMessage(
                videoRenderer, MediaCodecVideoTrackRenderer.MSG_SET_SURFACE, surface.getHolder().getSurface());
    }
}

@Override
public void onSingleManifestError(IOException e) {

}



@Override
public void onPlayWhenReadyCommitted() {

}

@Override
public void onPlayerError(ExoPlaybackException error) {

}

@Override
public void onLoadStarted(int sourceId, long length, int type, int trigger, Format format, long mediaStartTimeMs, long mediaEndTimeMs) {

}

@Override
public void onLoadCompleted(int sourceId, long bytesLoaded, int type, int trigger, Format format, long mediaStartTimeMs, long mediaEndTimeMs, long elapsedRealtimeMs, long loadDurationMs) {

}

@Override
public void onLoadCanceled(int sourceId, long bytesLoaded) {

}

@Override
public void onLoadError(int sourceId, IOException e) {

}

@Override
public void onUpstreamDiscarded(int sourceId, long mediaStartTimeMs, long mediaEndTimeMs) {

}

@Override
public void onDownstreamFormatChanged(int sourceId, Format format, int trigger, long mediaTimeMs) {

}

@Override
public void onAudioFocusChange(int focusChange) {

}


}

1 ответ

Вы должны обратиться отсюда ( http://google.github.io/ExoPlayer/doc/reference/), чтобы добавить / настроить управление воспроизведением мультимедиа.

PlaybackControlView может быть настроен путем установки атрибутов (или вызова соответствующих методов), переопределения файла макета представления или путем указания файла макета пользовательского представления, как описано ниже.

Другие вопросы по тегам