0

我正在开发 C# 应用程序,它将读取 .srt 文件并将其显示在屏幕上。

文件格式就是这样;

1   00:00:06,000    00:00:07,400    Enjoy the movie! 
2   00:00:07,500    00:00:09,500    Hi, my name is Mary
3   00:00:22,000    00:00:25,000    Hello my name is John.

我正在使用一个计时器,它每 100 毫秒滴答一次,并且在每个滴答声上,我都想检查值是否在开始和结束之间。在这种情况下,首先将在 00:00:06,000 和 00:00:07,400 之间。但我不确定我应该使用什么值。我试图将它解析为 DateTime 但它没有转换。

有什么想法吗?

4

3 回答 3

1

您可以使用DateTimeTimeSpan但您需要提供正确的格式才能ParseExact正常工作。

于 2012-05-18T04:10:43.807 回答
1

使用时间跨度。这里是简单的控制台项目,用于在正确的时间显示字幕

    class Program
    {
    private static Queue<Subtitle> _subtitles;

    private static Subtitle _activeSubtitle;

    private static TimeSpan _currentTime = new TimeSpan();

    static void Main(string[] args)
    {
        _subtitles = new Queue<Subtitle>();

        Subtitle title1 = new Subtitle()
                              {
                                  StartTime = TimeSpan.Parse("00:00:06,000"),
                                  EndTime =  TimeSpan.Parse("00:00:07,400"),
                                  Text = "Enjoy the movie!"
                              };

        Subtitle title2 = new Subtitle()
                              {
                                  StartTime = TimeSpan.Parse("00:00:07,500"),
                                  EndTime =  TimeSpan.Parse("00:00:09,500"),
                                  Text = "Hi, my name is Mary"
                              };

        Subtitle title3 = new Subtitle()
                              {
                                  StartTime = TimeSpan.Parse("00:00:22,000"),
                                  EndTime =  TimeSpan.Parse("00:00:25,000"),
                                  Text = "Hello my name is John."
                              };

        _subtitles.Enqueue(title1);
        _subtitles.Enqueue(title2);
        _subtitles.Enqueue(title3);

        Timer timer = new Timer(ShowSubtitles, null, 0, 100);

        while (_currentTime <= new TimeSpan(0, 0, 0, 30))
        {

        }
        Console.WriteLine("End");
    }

    private static void ShowSubtitles(object state)
    {

        if (_activeSubtitle == null && _subtitles.Count > 0)
            _activeSubtitle = _subtitles.Dequeue();
        Console.WriteLine(_currentTime);

        if (_activeSubtitle != null)
        {


            if (_currentTime >= _activeSubtitle.StartTime && _currentTime <= _activeSubtitle.EndTime)
                Console.WriteLine("\t{0}", _activeSubtitle.Text);

            if (_currentTime >= _activeSubtitle.EndTime)
                _activeSubtitle = null;
        }
        _currentTime = _currentTime.Add(new TimeSpan(0, 0, 0, 0, 100));

    }
}

internal class Subtitle
{
    public TimeSpan StartTime { get; set; }
    public TimeSpan EndTime { get; set; }
    public string Text { get; set; }
}
于 2012-05-18T04:51:40.293 回答
1

您必须使用 TimeSpan 类型进行解析,看看这里

于 2012-05-18T04:02:47.467 回答