Advertisement
ivandrofly

SubtitleEdit: Merge subtitles

Apr 2nd, 2025
388
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.55 KB | None | 0 0
  1. namespace Nikse.SubtitleEdit.Extensions
  2. {
  3.     public static class SubtitleExtensions
  4.     {
  5.         public static void Merge(this Subtitle subtitle, IEnumerable<Paragraph> paragraphs)
  6.         {
  7.             var mergingParagraphs = paragraphs.OrderBy(p => p.Number).ToArray();
  8.             if (mergingParagraphs.Length < 2)
  9.             {
  10.                 return;
  11.             }
  12.  
  13.             // check if sequential
  14.             if (!IsSequential(paragraphs))
  15.             {
  16.                 return;
  17.             }
  18.  
  19.             // Array.Sort(paragraphs, (p, other) => p.Number.CompareTo(other.Number));
  20.             var pivotParagraph = mergingParagraphs.First();
  21.             pivotParagraph.EndTime = mergingParagraphs.Last().EndTime;
  22.             pivotParagraph.Text = Utilities.AutoBreakLine(string.Join(Environment.NewLine, mergingParagraphs.Select(p => p.Text)));
  23.  
  24.             // note: this required that the paragraph number is sequential and starting from 1
  25.             subtitle.Paragraphs.RemoveRange(pivotParagraph.Number - 1, mergingParagraphs.Skip(1).Count());
  26.  
  27.             bool IsSequential(IEnumerable<Paragraph> sequentialParagraphs)
  28.             {
  29.                 int sequenceStart = sequentialParagraphs.First().Number;
  30.                 var range = Enumerable.Range(sequenceStart, sequentialParagraphs.Count());
  31.                 var indexedParagraph = sequentialParagraphs.Zip(range, (p, i) => new ValueTuple<int, Paragraph>(i, p));
  32.                 return sequentialParagraphs.Skip(1).All(p => p.Number == sequenceStart + 1);
  33.             }
  34.         }
  35.     }
  36. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement