標籤:視頻 ati rod soft oid art 讀取 ide key
前言
Microsoft Virtual Academy提供了學習ASP.NET的大量視頻材料。(注1)
由於視頻伺服器位于海外,國內瀏覽速度並不理想,幸好官方提供了視頻的以及英文字幕檔案。
然而其提供下載的字幕檔案僅為不帶時間戳記的文字文件,而頁面上提供的帶時間戳記的字幕檔案並非標準格式字幕檔案,因此用C#製作了一個簡單字幕製作程式。
需求
1.在提供的文本中提取字幕開始與結束時間戳記。由於官方字幕文檔只有開始時間,需要截取下一條字幕開始時間作為結束時間並進行微調;
2.將提取的時間戳記擴充為srt標準時間戳記格式。官方字幕的時間格式並不符合srt字幕需求的格式;
3.輸出標準格式的srt字幕檔案。
輸出結果如下,依次為原始的字幕文檔、準確的srt檔案、字幕添加到視頻中的效果(注2)
00:00:04We are back.00:00:04And we are almost to the MVC partof ASP.NET Core introduction,00:00:09not quite, but almost.00:00:11What we‘re gonna do here is we‘regonna give you a little bit...
100:00:03.00 --> 00:00:04.50We are back.200:00:04.55 --> 00:00:09.50And we are almost to the MVC partof ASP.NET Core introduction,300:00:09.55 --> 00:00:11.50not quite, but almost.400:00:11.55 --> 00:00:13.50What 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.第一條字幕由於時間較短以及官方時間戳記的不完整與第二字幕開始時間一致,需要經過手動微調。可以增加邏輯進行處理,然而只有一條字幕所以在本例沒有實現。
[C#]為微軟ASP.NET官方教學視頻增加字幕