android exoplayer 获取及设置字幕
获取字幕:
ExoPlayer提供了一个SubtitleView类,它可以用来显示字幕。要获取字幕,您需要做以下几步:
1.在您的布局文件中添加一个SubtitleView:
<com.google.android.exoplayer2.ui.SubtitleView
android:id="@+id/subtitle_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
2.在您的Activity或Fragment中,获取SubtitleView并设置它的播放器:
// 获取SubtitleView
SubtitleView subtitleView = findViewById(R.id.subtitle_view);
// 设置播放器
SimpleExoPlayer player = ExoPlayerFactory.newSimpleInstance(this);
player.setSubtitleView(subtitleView);
3.在您的ExoPlayer实例中,设置字幕轨道:
// 创建一个字幕轨道
MediaSource subtitleSource = new SingleSampleMediaSource(Uri.parse("file:///android_asset/subtitle.srt"),
new DefaultDataSourceFactory(this, "ExoPlayer"), Format.createTextSampleFormat(null, MimeTypes.APPLICATION_SUBRIP, null, Format.NO_VALUE, Format.NO_VALUE, "en", null), C.TIME_UNSET);
// 将字幕轨道添加到播放器
player.prepare(new MergingMediaSource(mediaSource, subtitleSource), true, false);
设置字幕:
要设置字幕,您需要做以下几步:
1.在您的ExoPlayer实例中,添加一个字幕轨道:
// 创建一个字幕轨道
MediaSource subtitleSource = new SingleSampleMediaSource(Uri.parse("file:///android_asset/subtitle.srt"),
new DefaultDataSourceFactory(this, "ExoPlayer"), Format.createTextSampleFormat(null, MimeTypes.APPLICATION_SUBRIP, null, Format.NO_VALUE, Format.NO_VALUE, "en", null), C.TIME_UNSET);
// 将字幕轨道添加到播放器
player.prepare(new MergingMediaSource(mediaSource, subtitleSource), true, false);
2.在您的布局文件中添加一个Button,用于切换字幕:
<Button
android:id="@+id/subtitle_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Subtitle" />
3.在您的Activity或Fragment中,获取Button并添加一个点击事件:
// 获取Button
Button subtitleButton = findViewById(R.id.subtitle_button);
// 添加点击事件
subtitleButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// 切换字幕
player.nextSubtitle();
}
});
原文地址: https://www.cveoy.top/t/topic/b7zW 著作权归作者所有。请勿转载和采集!