3

I am building Video player android app I want to add subtitle to the video the code was run successfully and the subtitle show correctly,but when I use the custom view by adding the exoplayerView layout to my project the subtitle disappears. so what should add to make the subtitle appear with the custom View note: I am using exoplayer2 this is my code:

public class MainActivity extends AppCompatActivity {

private boolean isShowingTrackSelectionDialog;
private SimpleExoPlayer player;
private SimpleExoPlayerView simpleExoPlayerView;
private ImageButton quality;
private TrackSelector trackSelector;
private Uri videoUri;
private Uri subtitleUri;



public void setVideoUri(String videoUri) {
    this.videoUri = Uri.parse(videoUri);
}


public void setSubtitleUri(String subtitleUri) {
    this.subtitleUri = Uri.parse(subtitleUri);
}




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //set link
    setSubtitleUri("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");
    setVideoUri("http://halasat2.vodu.me:80/vod/playlist_2_77636562545130.json/master.m3u8");

    //find view by id
    simpleExoPlayerView = findViewById(R.id.exoplayer);
    PlaybackControlView controlView = simpleExoPlayerView.findViewById(R.id.exo_controller);
    quality = controlView.findViewById(R.id.q);


    ///???????????
    DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter(); //test
    TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
    trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
    LoadControl loadControl = new DefaultLoadControl();


    //  Create the player

    player = ExoPlayerFactory.newSimpleInstance(this, trackSelector, loadControl);



    // Bind the player to the view.
    simpleExoPlayerView.setPlayer(player);

    // Produces DataSource instances through which media data is loaded.
    DataSource.Factory dataSourceFactory = new DefaultDataSourceFactory(this, Util.getUserAgent(this, "exoplayer2example"), bandwidthMeter);


    //FOR LIVESTREAM LINK:
    // MediaSource videoSource =new HlsMediaSource(videoUri,dataSourceFactory,1,null,null);
    MediaSource videoSource = new HlsMediaSource.Factory(dataSourceFactory).createMediaSource(videoUri);

    // 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.
            Format.NO_VALUE,
            "en",
            null); // The subtitle language. May be null.

    MediaSource subtitleSource = new SingleSampleMediaSource.Factory(dataSourceFactory).createMediaSource(subtitleUri, subtitleFormat, C.TIME_UNSET);
    //merging the video with subTitle
    MergingMediaSource mergedSource = new MergingMediaSource(videoSource, subtitleSource);
    //set the player to view
    simpleExoPlayerView.setPlayer(player);
    //prepare video with sub title
    player.prepare(mergedSource);


    //auto play
    player.setPlayWhenReady(false);
    changeQuality();
}

private void changeQuality() {
    quality.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (!isShowingTrackSelectionDialog
                    && TrackSelectionDialog.willHaveContent((DefaultTrackSelector) trackSelector)) {
                isShowingTrackSelectionDialog = true;
                TrackSelectionDialog trackSelectionDialog =
                        TrackSelectionDialog.createForTrackSelector(
                                (DefaultTrackSelector) trackSelector,
                                /* onDismissListener= */ dismissedDialog -> isShowingTrackSelectionDialog = false);
                trackSelectionDialog.show(getSupportFragmentManager(), /* tag= */ null);

            }
        }
    });

    simpleExoPlayerView.requestFocus();
}


//if the user close the activity then the video should pause also
@Override
protected void onPause() {
    super.onPause();
    //If Exo is ready, passing false you will pause the player
    player.setPlayWhenReady(false);
}


}

this is the layout

<?xml version="1.0" encoding="utf-8"?><!-- Copyright (C) 2016 The Android Open Source Project
     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
          http://www.apache.org/licenses/LICENSE-2.0
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->
<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <com.google.android.exoplayer2.ui.AspectRatioFrameLayout
        android:id="@id/exo_content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="center">

        <!-- Video surface will be inserted as the first child of the content frame. -->

        <View
            android:id="@id/exo_shutter"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@android:color/black" />

        <ImageView
            android:id="@id/exo_artwork"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:scaleType="fitXY" />



    </com.google.android.exoplayer2.ui.AspectRatioFrameLayout>

    <View
        android:id="@id/exo_controller_placeholder"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <com.google.android.exoplayer2.ui.SubtitleView
        android:id="@id/exo_subtitles"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <com.google.android.exoplayer2.ui.PlaybackControlView
        android:id="@id/exo_controller"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <FrameLayout
        android:id="@id/exo_overlay"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</merge>
RKRK
  • 1,284
  • 5
  • 14
  • 18
Enaam Riyadh
  • 131
  • 3
  • 15

3 Answers3

1

First of all Check if Your video contains subtitles or not and if it has subtitles then add this lines to your activity's onCreate() method

public static DefaultTrackSelector trackSelector;

DefaultBandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
TrackSelection.Factory videoTrackSelectionFactory = new 
AdaptiveTrackSelection.Factory(bandwidthMeter);
trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);

trackSelector.setParameters(new DefaultTrackSelector.ParametersBuilder()
                        .setRendererDisabled(C.TRACK_TYPE_VIDEO, false)
                        .build()
                );

This will shows subtitle. if you use "true" after C.TRACK_TYPE_VIDEO then it will disable subtitle and makes it invisible

Vivek Thummar
  • 395
  • 4
  • 17
0

I was just having the same problem; in my case, subtitle MediaSource was infact loading however because I was not using the ExoPlayerView I needed to add a TextOutput callback listener to bind the subtitles manually to my custom view.

Something like:

player.addTextOutputListener(cues -> {
 
    if (cues.size() > 1) {
        Logger.w(TAG, "There are more than one cues available.");
    }

    if (subtitleTextView != null && !cues.isEmpty()) {
        // Since an srt file will only ever have one cue we can afford to get only the first one.
        subtitleTextView.setText(cues.get(0).text);
    }
    else {
        subtitleTextView.setText("");
    }
});
Abbas
  • 3,529
  • 5
  • 36
  • 64
0

Refrence : - https://exoplayer.dev/media-items.html

USE Below Snippet Code

private void playWithCaption() {

        MediaItem.SubtitleConfiguration subtitle =
                new MediaItem.SubtitleConfiguration.Builder(subtitleUri)
                        .setMimeType(MimeTypes.APPLICATION_SUBRIP) // The correct MIME type (required).
                        .setLanguage("en") // MUST, The subtitle language (optional).
                        .setSelectionFlags(C.SELECTION_FLAG_DEFAULT) //MUST,  Selection flags for the track (optional).
                        .build();
        MediaItem mediaItem =
                new MediaItem.Builder()
                        .setUri(videoUri)
                        .setSubtitleConfigurations(ImmutableList.of(subtitle))
                        .build();

        player.setMediaItem(mediaItem);

        player.prepare();;


        player.setPlayWhenReady(true);

    }

use below Dependency

implementation "com.google.android.exoplayer:exoplayer:2.17.1"
implementation "com.google.android.exoplayer:exoplayer-core:2.17.1"
implementation "com.google.android.exoplayer:exoplayer-ui:2.17.1"

Build SDK Version Must be 31

Vinesh Chauhan
  • 1,288
  • 11
  • 27