C# 解析srt字幕文件

github上找的 这种东西太简单了 自己随便写也没什么关系

https://github.com/roguecode/Unity-Simple-SRT/blob/master/src/Assets/SimpleSRT/SRTParser.cs

其中 GetForTime函数 会移除 超过时间得字幕 如果重新播放视频得话需要重新加载字幕 可以改成下面得函数

    public SubtitleBlock GetForTime(float time)
    {
        if (_subtitles.Count > 0)
        {
            var tmp = _subtitles.Find(sub => time >= sub.From && time <= sub.To);
            if (tmp == null)
            {
                return SubtitleBlock.Blank;
            }
            else
            {
                return tmp;
            }
        }
        return SubtitleBlock.Blank;
    }
using System;
using System.Collections.Generic;
using UnityEngine;

public class SRTParser
{
  List<SubtitleBlock> _subtitles;
  public SRTParser(string textAssetResourcePath)
  {
    var text = Resources.Load<TextAsset>(textAssetResourcePath);
    Load(text);
  }

  public SRTParser(TextAsset textAsset)
  {
    this._subtitles = Load(textAsset);
  }

  static public List<SubtitleBlock> Load(TextAsset textAsset)
  {
    if (textAsset == null)
    {
      Debug.LogError("Subtitle file is null");
      return null;
    }

    var lines = textAsset.text.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);

    var currentState = eReadState.Index;

    var subs = new List<SubtitleBlock>();

    int currentIndex = 0;
    double currentFrom = 0, currentTo = 0;
    var currentText = string.Empty;
    for (var l = 0; l < lines.Length; l++)
    {
      var line = lines[l];

      switch (currentState)
      {
        case eReadState.Index:
          {
            int index;
            if (Int32.TryParse(line, out index))
            {
              currentIndex = index;
              currentState = eReadState.Time;
            }
          }
          break;
        case eReadState.Time:
          {
            line = line.Replace(',', '.');
            var parts = line.Split(new[] { "-->" }, StringSplitOptions.RemoveEmptyEntries);

            // Parse the timestamps
            if (parts.Length == 2)
            {
              TimeSpan fromTime;
              if (TimeSpan.TryParse(parts[0], out fromTime))
              {
                TimeSpan toTime;
                if (TimeSpan.TryParse(parts[1], out toTime))
                {
                  currentFrom = fromTime.TotalSeconds;
                  currentTo = toTime.TotalSeconds;
                  currentState = eReadState.Text;
                }
              }
            }
          }
          break;
        case eReadState.Text:
          {
            if (currentText != string.Empty)
                currentText += "\r\n";

            currentText += line;

            // When we hit an empty line, consider it the end of the text
            if (string.IsNullOrEmpty(line) || l == lines.Length - 1)
            {
              // Create the SubtitleBlock with the data we've aquired 
              subs.Add(new SubtitleBlock(currentIndex, currentFrom, currentTo, currentText));

              // Reset stuff so we can start again for the next block
              currentText = string.Empty;
              currentState = eReadState.Index;
            }
          }
          break;
      }
    }
    return subs;
  }

  public SubtitleBlock GetForTime(float time)
  {
    if (_subtitles.Count > 0)
    {
      var subtitle = _subtitles[0];

      if (time >= subtitle.To)
      {
        _subtitles.RemoveAt(0);

        if (_subtitles.Count == 0)
          return null;

        subtitle = _subtitles[0];
      }

      if (subtitle.From > time)
        return SubtitleBlock.Blank;

      return subtitle;
    }
    return null;
  }

  enum eReadState
  {
    Index,
    Time,
    Text
  }
}

public class SubtitleBlock
{
  static SubtitleBlock _blank;
  public static SubtitleBlock Blank
  {
    get { return _blank ?? (_blank = new SubtitleBlock(0, 0, 0, string.Empty)); }
  }
  public int Index { get; private set; }
  public double Length { get; private set; }
  public double From { get; private set; }
  public double To { get; private set; }
  public string Text { get; private set; }

  public SubtitleBlock(int index, double from, double to, string text)
  {
    this.Index = index;
    this.From = from;
    this.To = to;
    this.Length = to - from;
    this.Text = text;
  }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • # Awesome Python [![Awesome](https://cdn.rawgit.com/sindr...
    emily_007阅读 2,227评论 0 3
  • 本文转载自:https://handong1587.github.io/deep_learning/2015/10...
    Kwan_SS阅读 4,098评论 0 3
  • 今天有点咸🐟想做一只没有梦想的搬运工 十六进制编辑器 十六进制编辑器(二进制文件编辑器或字节编辑器)是一种允许操纵...
    Honny_Boo阅读 2,501评论 0 7
  • 你回来了。在这仲春时节,你随着暖流回到北方的黑土地。 归来的人啊,你是不是听到了故乡的召唤?春雷滚滚,每一串轰响都...
    静铃音阅读 233评论 0 3
  • 匆匆一年,转瞬又到了年底,这个时候总是忙碌的,年终总结要写,新一年的工作计划要做,还要准备年会,日子过的喧...
    漠然_然阅读 143评论 0 3