Another solution will be to use the 'DispatcherTimer' control to sync your titles -
C# DispatcherTimer properties[
^]
Your code will look like the following, adjust the 'SubtitleRecord' class and initialization parts based on your actual data in your list -
using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Threading;
namespace SubtitleSyncApp
{
public partial class MainWindow : Window
{
private List<SubtitleRecord> subtitleList = new List<SubtitleRecord>();
private DispatcherTimer subtitleTimer = new DispatcherTimer();
private int currentIndex = 0;
public MainWindow()
{
InitializeComponent();
InitializeSubtitleList();
videoPlayer.MediaOpened += VideoPlayer_MediaOpened;
subtitleTimer.Interval = TimeSpan.FromMilliseconds(100);
subtitleTimer.Tick += SubtitleTimer_Tick;
}
private void VideoPlayer_MediaOpened(object sender, RoutedEventArgs e)
{
subtitleTimer.Start();
}
private void SubtitleTimer_Tick(object sender, EventArgs e)
{
double currentPosition = videoPlayer.Position.TotalSeconds;
while (currentIndex < subtitleList.Count - 1 && currentPosition > subtitleList[currentIndex + 1].StartTime)
{
currentIndex++;
}
subtitleTextBlock.Text = subtitleList[currentIndex].SubtitleText;
}
private void InitializeSubtitleList()
{
for (int i = 0; i < 1000; i++)
{
subtitleList.Add(new SubtitleRecord
{
StartTime = i * 5,
EndTime = (i + 1) * 5,
SubtitleText = $"Subtitle {i + 1}"
});
}
}
}
public class SubtitleRecord
{
public double StartTime { get; set; }
public double EndTime { get; set; }
public string SubtitleText { get; set; }
}
}