I want to download .ts links in m3u8 before they expire. I am able to open m3u8 file with vlc player but using mediatoolkit it does not download .ts links to download. I will merge the ts files into one video later. Please help I only know c#
public class M3U8Processor
{
public static void DownloadSegmentsFromM3U8(string m3u8Content)
{
List<string> segmentUrls = ParseM3U8(m3u8Content);
string savePath = Path.Combine(Directory.GetCurrentDirectory(), "records");
DownloadSegments(segmentUrls, savePath);
}
private static List<string> ParseM3U8(string m3u8Content)
{
List<string> segmentUrls = new List<string>();
string[] lines = m3u8Content.Split('\n'); // Split \n
foreach (string line in lines)
{
if (!line.StartsWith("#EXT"))
{
segmentUrls.Add(line.Trim()); // Trim
}
}
return segmentUrls;
}
private static void DownloadSegments(List<string> segmentUrls, string savePath)
{
using (var engine = new Engine())
{
for (int i = 0; i < segmentUrls.Count; i++)
{
string segmentUrl = segmentUrls[i];
bool isValidUrl = UrlValidator.IsUrlValid(segmentUrl);
Console.WriteLine("isValidUrl: " + isValidUrl);
string fileName = $"{i + 1}.ts";
try
{
var inputFile = new MediaFile { Filename = segmentUrl };
var outputFile = new MediaFile { Filename = Path.Combine(savePath, fileName) };
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(0) };
engine.Convert(inputFile, outputFile, options);
Console.WriteLine($"Segment {i + 1} downloaded and saved successfully.");
}
catch (Exception ex)
{
Console.WriteLine($"Error downloading segment {i + 1}: {ex.Message}");
}
}
}
}