首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Exoplayer android中为视频添加字幕(.SRT文件)?

如何在Exoplayer android中为视频添加字幕(.SRT文件)?
EN

Stack Overflow用户
提问于 2017-02-20 20:35:25
回答 6查看 12K关注 0票数 10

我正在做一个项目,在这个项目中我应该在安卓系统中播放.srt文件和视频。我正在处理Exoplayer的示例,但无法播放带有视频的.srt文件。

我使用的代码是,

代码语言:javascript
复制
MediaSource mediaSource = new HlsMediaSource(Uri.parse("https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8"),
                mediaDataSourceFactory, mainHandler, null);

         Format textFormat = Format.createTextSampleFormat(null, MimeTypes.APPLICATION_SUBRIP,
                null, Format.NO_VALUE, Format.NO_VALUE, "en", null);

        Uri uri = Uri.parse("http://www.storiesinflight.com/js_videosub/jellies.srt");


        MediaSource subtitleSource = new SingleSampleMediaSource(uri, mediaDataSourceFactory, textFormat, C.TIME_UNSET);
// Plays the video with the sideloaded subtitle.
        MergingMediaSource mergedSource =
                new MergingMediaSource(mediaSource, subtitleSource);

        player.prepare(mergedSource);

谁可以建议我解决这个或任何教程链接相同。非常感谢您的帮助!

EN

回答 6

Stack Overflow用户

发布于 2018-05-20 18:11:36

我知道现在回答这个问题为时已晚,但如果其他人上当了,试试这个:

代码语言:javascript
复制
public class MainActivity extends AppCompatActivity {
SimpleExoPlayerView exoPlayerView;
SimpleExoPlayer exoPlayer;
String videoURL = "http://blueappsoftware.in/layout_design_android_blog.mp4";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    exoPlayerView = (SimpleExoPlayerView) findViewById(R.id.exo_player_view);
    try {


        BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        TrackSelector trackSelector = new DefaultTrackSelector(new AdaptiveTrackSelection.Factory(bandwidthMeter));
        exoPlayer = ExoPlayerFactory.newSimpleInstance(this, trackSelector);

        Uri videoURI = Uri.parse(videoURL);
        Uri subtitleUri=Uri.parse("https://firebasestorage.googleapis.com/v0/b/findandfix-2f4a9.appspot.com/o/Despacito%20Remix%20Luis%20Fonsi%20ft.Daddy%20Yankee%20Justin%20Bieber%20Lyrics%20%5BSpanish%5D.srt?alt=media&token=63344d04-af1c-4e2c-9d15-381bf7159308");
        DefaultHttpDataSourceFactory dataSourceFactory = new DefaultHttpDataSourceFactory("exoplayer_video");

        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
        MediaSource mediaSource = new ExtractorMediaSource(videoURI, dataSourceFactory, extractorsFactory, null, null);

        // Build the subtitle MediaSource.
        Format subtitleFormat = Format.createTextSampleFormat(
                null, // An identifier for the track. May be null.
                MimeTypes.APPLICATION_SUBRIP, // The mime type. Must be set correctly.
                null,
                Format.NO_VALUE,
                Format.NO_VALUE,
                "en",
                null); // The subtitle language. May be null.

        MediaSource subtitleSource =new SingleSampleMediaSource(subtitleUri, dataSourceFactory, subtitleFormat, C.TIME_UNSET);

        MergingMediaSource mergedSource =
                new MergingMediaSource(mediaSource, subtitleSource);

        exoPlayerView.setPlayer(exoPlayer);
        exoPlayer.prepare(mergedSource);
        exoPlayer.setPlayWhenReady(true);
    }catch (Exception e){
        Log.e("MainAcvtivity"," exoplayer error "+ e.toString());
    }

}

}

票数 4
EN

Stack Overflow用户

发布于 2017-04-30 14:40:12

我只是编辑exoplayer示例在那里的播放器活动,如…这对我来说很有效。

代码语言:javascript
复制
 private void initializePlayer() {
        Intent intent = getIntent();
        if (player == null) {
            boolean preferExtensionDecoders = intent.getBooleanExtra(PREFER_EXTENSION_DECODERS, false);
            UUID drmSchemeUuid = intent.hasExtra(DRM_SCHEME_UUID_EXTRA)
                    ? UUID.fromString(intent.getStringExtra(DRM_SCHEME_UUID_EXTRA)) : null;
            DrmSessionManager<FrameworkMediaCrypto> drmSessionManager = null;
            if (drmSchemeUuid != null) {
                String drmLicenseUrl = intent.getStringExtra(DRM_LICENSE_URL);
                String[] keyRequestPropertiesArray = intent.getStringArrayExtra(DRM_KEY_REQUEST_PROPERTIES);
                Map<String, String> keyRequestProperties;
                if (keyRequestPropertiesArray == null || keyRequestPropertiesArray.length < 2) {
                    keyRequestProperties = null;
                } else {
                    keyRequestProperties = new HashMap<>();
                    for (int i = 0; i < keyRequestPropertiesArray.length - 1; i += 2) {
                        keyRequestProperties.put(keyRequestPropertiesArray[i],
                                keyRequestPropertiesArray[i + 1]);
                    }
                }
                try {
                    drmSessionManager = buildDrmSessionManager(drmSchemeUuid, drmLicenseUrl,
                            keyRequestProperties);
                } catch (UnsupportedDrmException e) {
                    int errorStringId = Util.SDK_INT < 18 ? R.string.error_drm_not_supported
                            : (e.reason == UnsupportedDrmException.REASON_UNSUPPORTED_SCHEME
                            ? R.string.error_drm_unsupported_scheme : R.string.error_drm_unknown);
                    showToast(errorStringId);
                    return;
                }
            }

            @SimpleExoPlayer.ExtensionRendererMode int extensionRendererMode =
                    ((AppController) getApplication()).useExtensionRenderers()
                            ? (preferExtensionDecoders ? SimpleExoPlayer.EXTENSION_RENDERER_MODE_PREFER
                            : SimpleExoPlayer.EXTENSION_RENDERER_MODE_ON)
                            : SimpleExoPlayer.EXTENSION_RENDERER_MODE_OFF;
            TrackSelection.Factory videoTrackSelectionFactory =
                    new AdaptiveVideoTrackSelection.Factory(BANDWIDTH_METER);
            trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
            trackSelectionHelper = new TrackSelectionHelper(trackSelector, videoTrackSelectionFactory);
            player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, new DefaultLoadControl(),
                    drmSessionManager, extensionRendererMode);
            player.addListener(this);

            eventLogger = new EventLogger(trackSelector);
            player.addListener(eventLogger);
            player.setAudioDebugListener(eventLogger);
            player.setVideoDebugListener(eventLogger);
            player.setMetadataOutput(eventLogger);

            simpleExoPlayerView.setPlayer(player);
            player.setPlayWhenReady(shouldAutoPlay);
            debugViewHelper = new DebugTextViewHelper(player, debugTextView);
            debugViewHelper.start();
            playerNeedsSource = true;


        }
        if (playerNeedsSource) {
            String action = intent.getAction();
            Log.d("URL action: ", action);
            Uri[] uris;
            String[] extensions;
            if (ACTION_VIEW.equals(action)) {
                uris = new Uri[] {intent.getData()};
                extensions = new String[] {intent.getStringExtra(EXTENSION_EXTRA)};
            } else if (ACTION_VIEW_LIST.equals(action)) {
                String[] uriStrings = intent.getStringArrayExtra(URI_LIST_EXTRA);
                uris = new Uri[uriStrings.length];
                for (int i = 0; i < uriStrings.length; i++) {
                    uris[i] = Uri.parse(uriStrings[i]);
                    Log.d("URL action2: ", String.valueOf(uris[i])+" ");
                }
                extensions = intent.getStringArrayExtra(EXTENSION_LIST_EXTRA);
                if (extensions == null) {
                    extensions = new String[uriStrings.length];
                }
            } else {
                showToast(getString(R.string.unexpected_intent_action, action));
                return;
            }
            if (Util.maybeRequestReadExternalStoragePermission(this, uris)) {
                // The player will be reinitialized if the permission is granted.
                return;
            }
            MediaSource[] mediaSources = new MediaSource[uris.length];
            for (int i = 0; i < uris.length; i++) {
                mediaSources[i] = buildMediaSource(uris[i], extensions[i]);
                Log.d("URL action extensions: ", String.valueOf( extensions[i]));
            }
            MediaSource mediaSource = mediaSources.length == 1 ? mediaSources[0]
                    : new ConcatenatingMediaSource(mediaSources);
            boolean haveResumePosition = resumeWindow != C.INDEX_UNSET;
            if (haveResumePosition) {
                player.seekTo(resumeWindow, resumePosition);
            }
            // edit for subtitle
           // player.prepare(mediaSource, !haveResumePosition, false);
         //   playerNeedsSource = false;
          // player.seekTo(0);
            //updateButtonVisibilities();

           /* MediaSource mediaSource = new HlsMediaSource(Uri.parse("https://bitdash-a.akamaihd.net/content/sintel/hls/playlist.m3u8"),
                    mediaDataSourceFactory, mainHandler, null);*/

            Format textFormat = Format.createTextSampleFormat(null, MimeTypes.APPLICATION_SUBRIP,
                    null, Format.NO_VALUE, Format.NO_VALUE, "en", null);

            Uri uri = Uri.parse("http://www.storiesinflight.com/js_videosub/jellies.srt");


            MediaSource subtitleSource = new SingleSampleMediaSource(uri, mediaDataSourceFactory, textFormat, C.TIME_UNSET);
// Plays the video with the sideloaded subtitle.
            MergingMediaSource mergedSource =
                    new MergingMediaSource(mediaSource, subtitleSource);

            player.prepare(mergedSource,!haveResumePosition, false);
            playerNeedsSource = false;
            //player.seekTo(0);
        }


    }
票数 3
EN

Stack Overflow用户

发布于 2018-08-07 14:47:06

代码语言:javascript
复制
SubtitleView subtitleView=(SubtitleView)findViewById(com.google.android.exoplayer2.R.id.exo_subtitles); 
player.setTextOutput(new ComponentListener());

public class ComponentListener implements TextRenderer.Output{
  @Override
  public void onCues(List<Cue> cues) {
    if (subtitleView != null) {
        subtitleView.onCues(cues);
    }
  }

}

要显示/隐藏subtitleView:

代码语言:javascript
复制
subtitleView.setVisiblity(Visible/Gone);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42344779

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档