C#读取SRT字幕文件
之前自己做了一个小的播放器软件,缺少字幕的功能有时候很不方面,研究了一下,把SRT字幕的功能加上了。
SRT本身其实就是一个纯文本文件,只需要按照他的规则去解析就可以了。
附上我的实现代码,供大家参考:
using JcPlayer.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JcPlayer.Helpers { /// <summary> /// 解析字幕文件 /// </summary> public class SrtHelper { //定义一个ModelList的列表用于接受从文件读取的内容 private static List<SrtModel> mySrtModelList; //定义一个获取当前时间显示的string的方法 public static string GetTimeString(int timeMile) { String currentTimeTxt = ""; if (mySrtModelList != null) { foreach (SrtModel sm in mySrtModelList) { if (timeMile > sm.BeginTime && timeMile < sm.EndTime) { currentTimeTxt = sm.SrtString; } } } return currentTimeTxt; } /// <summary> /// 读取文件中的内容到mySrtModelList列表 /// </summary> /// <param name="srtPath">srt文件路径</param> /// <returns></returns> public static List<SrtModel> ParseSrt(string srtPath) { mySrtModelList = new List<SrtModel>(); string line; using (FileStream fs = new FileStream(srtPath, FileMode.Open)) { using (StreamReader sr = new StreamReader(fs, Encoding.Default)) { StringBuilder sb = new StringBuilder(); while ((line = sr.ReadLine()) != null) { if (!line.Equals("")) { sb.Append(line).Append("@"); continue; } string[] parseStrs = sb.ToString().Split('@'); if (parseStrs.Length < 3) { sb.Remove(0, sb.Length);// 清空,否则影响下一个字幕元素的解析</i> continue; } SrtModel srt = new SrtModel(); string strToTime = parseStrs[1]; int beginHour = int.Parse(strToTime.Substring(0, 2)); int begin_mintue = int.Parse(strToTime.Substring(3, 2)); int begin_scend = int.Parse(strToTime.Substring(6, 2)); int begin_milli = int.Parse(strToTime.Substring(9, 3)); int beginTime = (beginHour * 3600 + begin_mintue * 60 + begin_scend) * 1000 + begin_milli; int end_hour = int.Parse(strToTime.Substring(17, 2)); int end_mintue = int.Parse(strToTime.Substring(20, 2)); int end_scend = int.Parse(strToTime.Substring(23, 2)); int end_milli = int.Parse(strToTime.Substring(26, 2)); int endTime = (end_hour * 3600 + end_mintue * 60 + end_scend) * 1000 + end_milli; srt.BeginTime = beginTime; srt.EndTime = endTime; string strBody = null; for (int i = 2; i < parseStrs.Length; i++) { strBody += parseStrs[i]; } srt.SrtString = strBody; mySrtModelList.Add(srt); sb.Remove(0, sb.Length); } } } return mySrtModelList; } } }
代码中用到的数据类:
namespace JcPlayer.Models { /// <summary> /// 定义一个StrModel的类,用于接受从srt文件读取的文件格式 /// </summary> public class SrtModel { public int BeginTime { get; set; } public int EndTime { get; set; } public string SrtString { get; set; } public int Index { get; set; } } }