I'm working on a UWP Desktop application for playing videos. I need to include subtitles at runtime and I'm trying to use a TimedMetadataTrack object of type Subtitle. Although I've included several TimedTextCue in a TimedMetadataTrack object and added this object to the MediaSource's ExternalTimedMetadataTracks collection, no caption is displayed while the video plays on the MediaPlayerElement. What is missing? Any help is most welcome. Thanks.
XAML
<MediaPlayerElement x:Name="mediaPlayerElement"
AutoPlay="False"
Margin="5"
Width="640" Height="480"
HorizontalAlignment="Center"
AreTransportControlsEnabled="True" />
Code Behind
var source = MediaSource.CreateFromUri(new Uri("ms-appx:///Assets/teste.mp4"));
TimedMetadataTrack metadataTrack = new TimedMetadataTrack("ID_0", "en-us", TimedMetadataKind.Subtitle);
for (int i = 0; i < 10; i++)
{
TimedTextCue ttc = new TimedTextCue();
TimedTextLine ttl = new TimedTextLine();
ttl.Text = "This is subtitles line: " + i.ToString() + ".";
ttc.Id = "ID_" + i;
ttc.Lines.Add(ttl);
ttc.StartTime = TimeSpan.FromSeconds((i * 10) + 1);
ttc.Duration = TimeSpan.FromSeconds(10);
metadataTrack.AddCue(ttc);
}
source.ExternalTimedMetadataTracks.Add(metadataTrack);
this.mediaPlayerElement.Source = source;
is there a way to select the subtitle via programming, so that the user doesn't have to do this?
You could create a MediaPlaybackItem Class as the media source, then you could call the MediaPlaybackItem object's SetPresentationMode method, passing in the index of the track you want to toggle, and then providing a value from the TimedMetadataTrackPresentationMode enumeration.
Like this:
source.ExternalTimedMetadataTracks.Add(metadataTrack);
MediaPlaybackItem mediaPlaybackItem = new MediaPlaybackItem(source);
mediaPlayerElement.Source = mediaPlaybackItem;
mediaPlayerElement.AutoPlay = true;
mediaPlaybackItem.TimedMetadataTracks.SetPresentationMode(0, TimedMetadataTrackPresentationMode.PlatformPresented);
You could refer to this documentation for more information: Media items, playlists, and tracks.