[C#]为微软ASP.NET官方教学视频增加字幕

前言

Microsoft Virtual Academy提供了学习ASP.NET的大量视频材料。(注1)

由于视频服务器位于海外,国内浏览速度并不理想,幸好官方提供了视频的下载地址以及英文字幕文件。

然而其提供下载的字幕文件仅为不带时间戳的文本文档,而页面上提供的带时间戳的字幕文件并非标准格式字幕文件,因此用C#制作了一个简单字幕制作程序。

需求

1.在提供的文本中提取字幕开始与结束时间戳。由于官方字幕文档只有开始时间,需要截取下一条字幕开始时间作为结束时间并进行微调;

2.将提取的时间戳扩展为srt标准时间戳格式。官方字幕的时间格式并不符合srt字幕需求的格式;

3.输出标准格式的srt字幕文件。

输出结果如下,依次为原始的字幕文档、准确的srt文件、字幕添加到视频中的效果(注2)

00:00:04	We are back.
00:00:04	And we are almost to the MVC partof ASP.NET Core introduction,
00:00:09	not quite, but almost.
00:00:11	What we're gonna do here is we'regonna give you a little bit...

  

1
00:00:03.00 --> 00:00:04.50
We are back.
2
00:00:04.55 --> 00:00:09.50
And we are almost to the MVC partof ASP.NET Core introduction,
3
00:00:09.55 --> 00:00:11.50
not quite, but almost.
4
00:00:11.55 --> 00:00:13.50
What we're gonna do here is we'regonna give you a little bit...

  

  

  

实现

using System.IO;

namespace TxtToSrtForVideoOnASP.NET
{
    class Program
    {
        static void Main(string[] args)
        {
            //读取与输出文件
            string path = @"D:\transcript.txt";
            string subPath = @"D:\sub.srt";

            using (StreamWriter sw=new StreamWriter(subPath))
            {
                string[] allLine = File.ReadAllLines(path);                
                string startTime="";
                string endTime = "";
                for (int i = 0; i < allLine.Count(); i++)
                {
                    //读取每行前8个字符作为每条字幕开始时间
                    startTime = AdjustTime(allLine[i].Substring(0, 8), true);

                    //读取下一行前8个字符作为每条字幕结束时间
                    if (i == (allLine.Count()-1))
                        //视频结束时间
                        endTime = "00:19:24,00";
                    else
                        endTime= AdjustTime(allLine[i+1].Substring(0, 8), false);

                    //输出标准srt格式字幕
                    sw.WriteLine((i + 1) + "\r\n" + startTime + " --> " + endTime + "\r\n" + allLine[i].Substring(9));                     
                }                       
            }
            Console.WriteLine("输出完毕");
            Console.ReadKey();
        }

        /// <summary>
        /// 为srt文件提供完整的时间戳格式,加入少量延迟使字幕时间更准确
        /// </summary>
        /// <param name="Time">从transcript.txt中读取的时间戳</param>
        /// <param name="start">Time是否为开始时间</param>
        /// <returns></returns>
        public static string AdjustTime(string Time,bool start)
        {
            if (start)
                return (TimeSpan.Parse(Time) + TimeSpan.FromSeconds(0.55)).ToString().Substring(0,11);
            else
                return (TimeSpan.Parse(Time) + TimeSpan.FromSeconds(0.5)).ToString().Substring(0,11);
        }
    }
}

注:

1.https://mva.microsoft.com/en-US/training-courses/introduction-to-asp-net-core-1-0-16841?l=yiobVeE6C_3506218965

2.第一条字幕由于时间较短以及官方时间戳的不完整与第二字幕开始时间一致,需要经过手动微调。可以增加逻辑进行处理,然而只有一条字幕所以在本例没有实现。

原文地址:https://www.cnblogs.com/mirageJ/p/6359908.html