Exoplayer 2 - 如何在没有uri但有字符串的情况下显示字幕?



我想用 exoplayer 2 显示预加载的字幕,并向玩家提供一个基于 webvtt 的字符串,以便它处理字幕。

我的系统应该这样工作:

  1. 我向我的服务器发送请求以获取字幕(加密(
  2. 我解密服务器响应以获取字幕字符串(webvtt格式(
  3. 我想把这串串子送给外星人。Exoplayer应该能够显示潜艇,就好像我正在使用webvtt uri一样。

我不想使用系统文件,因为它会使用户可以访问字幕文件。


请参阅下面的活动代码:

//Class Player Activity
// ... activity code ...
public void initializePlayer(){
//... code intialization of player ...
mVideoEventListener = new VideoEventListener(this);
if(mEpisode.getVideo().getSubtitle() == null) {
mEpisode.getVideo().loadSubtitle(this, Video.VO, mVideoEventListener);
return;
}
hasSubtitle = true;
startPlayer();
}
public void startPlayer(){
boolean haveStartPosition = startWindow != C.INDEX_UNSET;
if (haveStartPosition) {
mPlayer.seekTo(startWindow, startPosition);
}
if(hasVideo && hasSubtitle){
MergingMediaSource mergedSource = new MergingMediaSource(mVideoSource, mSubtitleSource);
mPlayer.prepare(mergedSource, !haveStartPosition, false);
}
}
// ... activity code ...
private class VideoEventListener implements
Video.SubtitleListener,
LoadBalancer.OnLoadBalanceListener{
private final Context mCtx;
VideoEventListener(Context ctx) {
mCtx = ctx;
}
@Override
public void onSubtitleLoaded(String subtitle) {
hasSubtitle = true;
Format subtitleFormat = Format.createTextSampleFormat(null, MimeTypes.TEXT_VTT, C.SELECTION_FLAG_FORCED, "fr");
mSubtitleSource = //My problem : How create a mediaSource with variable "subtitle" in format WebVTT ?
startPlayer();
}
}

我在代码下面找到了答案:

@Override
public void onSubtitleLoaded(String s) {
hasSubtitle = true;
Format subtitleFormat = Format.createTextSampleFormat(
"test", MimeTypes.TEXT_VTT, C.SELECTION_FLAG_FORCED, "fr");
mSubtitleSource =
new SingleSampleMediaSource.Factory(new CustomDataSourceFactory(ctx, null, s.getBytes()))
.createMediaSource(Uri.parse(""), subtitleFormat, C.TIME_UNSET);
}

自定义数据源工厂类

public class CustomDataSourceFactory implements DataSource.Factory {
private final Context context;
private final @Nullable TransferListener listener;
private byte[] subtitles;
public CustomDataSourceFactory(
Context context,
@Nullable TransferListener listener,
byte[] subtitles) {
this.context = context.getApplicationContext();
this.subtitles = subtitles;
this.listener = listener;
}
@Override
public DataSource createDataSource() {
ByteArrayDataSource dataSource = new ByteArrayDataSource(subtitles);
if (listener != null) {
dataSource.addTransferListener(listener);
}
return dataSource;
}
}

相关内容

  • 没有找到相关文章

最新更新