exoplayer2 显示内嵌字幕
要在ExoPlayer 2中显示内嵌字幕,您可以使用以下步骤:
- 创建一个
DefaultTrackSelector对象,并将其分配给您的ExoPlayer实例:
DefaultTrackSelector trackSelector = new DefaultTrackSelector();
player = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
- 使用
MediaSource对象创建您的ExoPlayer实例:
MediaSource mediaSource = new ExtractorMediaSource.Factory(dataSourceFactory)
.createMediaSource(uri);
player.prepare(mediaSource);
- 如果您的媒体文件包含内嵌字幕,则它们将自动加载。您可以使用以下代码检查当前媒体源是否包含字幕轨道:
MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();
if (mappedTrackInfo != null) {
int rendererIndex = ...; // The index of the renderer for which you want to check the track selection.
int trackType = C.TRACK_TYPE_TEXT;
TrackGroupArray trackGroups = mappedTrackInfo.getTrackGroups(rendererIndex);
if (trackGroups.length > 0) {
TrackGroup trackGroup = trackGroups.get(0);
for (int i = 0; i < trackGroup.length; i++) {
Format format = trackGroup.getFormat(i);
if (format.sampleMimeType != null && format.sampleMimeType.startsWith("text/")) {
// This track group contains a text track.
}
}
}
}
- 如果您想手动选择字幕轨道,您可以使用以下代码:
MappedTrackInfo mappedTrackInfo = trackSelector.getCurrentMappedTrackInfo();
if (mappedTrackInfo != null) {
int rendererIndex = ...; // The index of the renderer for which you want to select a track.
int trackType = C.TRACK_TYPE_TEXT;
TrackGroupArray trackGroups = mappedTrackInfo.getTrackGroups(rendererIndex);
if (trackGroups.length > 0) {
int trackIndex = ...; // The index of the track you want to select.
DefaultTrackSelector.ParametersBuilder builder = trackSelector.buildUponParameters();
builder.setRendererDisabled(rendererIndex, false);
builder.setSelectionOverride(rendererIndex, trackGroups, new DefaultTrackSelector.SelectionOverride(trackIndex, 0));
trackSelector.setParameters(builder.build());
}
}
这将启用指定的渲染器,并选择指定的轨道。请注意,此代码仅选择单个轨道。如果您想同时选择多个轨道,请参阅ExoPlayer文档中的更多信息
原文地址: https://www.cveoy.top/t/topic/ca0C 著作权归作者所有。请勿转载和采集!