how to use DASH or HLS to play video in asp.net core?

mc 5,511 Reputation points
2023-09-01T02:44:22.8566667+00:00

how to upload video and then play it using DASH or HLS?

Developer technologies | ASP.NET | ASP.NET Core
{count} votes

Accepted answer
  1. Anonymous
    2023-09-05T11:37:54.1366667+00:00

    Hi @mc,

    Please follow my steps to implement this feature.

    1.Create a VideoController.cs. So that we can upload the video files and slice it by using ffmpeg.

    using AspCore7_Web_Identity.Areas.Identity.Data;
    using AspCore7_Web_Identity.Models;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.Extensions.Hosting.Internal;
    using System.Diagnostics;
    
    namespace AspCore7_Web_Identity.Controllers
    {
        public class VideoController : Controller
        {
            private readonly IHostEnvironment _hostingEnvironment;
    
            public VideoController(IHostEnvironment hostingEnvironment)
            {
                _hostingEnvironment = hostingEnvironment;
            }
            public IActionResult Index()
            {
                return View();
            }
            public IActionResult Upload()
            {
                return View();
            }
    
    
            [HttpPost]
            public IActionResult Upload(VideoUploadModel model)
            {
                if (model.File == null || model.File.Length == 0)
                    return BadRequest("No file uploaded.");
    
                var uploadPath = Path.Combine(_hostingEnvironment.ContentRootPath,"wwwroot" ,"uploads");
                if (!Directory.Exists(uploadPath))
                    Directory.CreateDirectory(uploadPath);
    
                var filePath = Path.Combine(uploadPath, model.File.FileName);
                using (var fileStream = new FileStream(filePath, FileMode.Create))
                {
                    model.File.CopyTo(fileStream);
                }
                // Create folder for files
                if (!Directory.Exists(Path.Combine(uploadPath,"hls", model.File.FileName)))
                    Directory.CreateDirectory(Path.Combine(uploadPath, "hls", model.File.FileName));
                // Convert the uploaded video to HLS format using FFmpeg
                ConvertToHls(filePath, Path.Combine(uploadPath, "hls", model.File.FileName , Path.GetFileNameWithoutExtension(model.File.FileName)));
    
                return Ok("Video processed and saved successfully.");
            }
    
            private void ConvertToHls(string inputPath, string outputPath)
            {
                
                var arguments = $"-i \"{inputPath}\" -c:v libx264 -b:v 1M -hls_time 10 -hls_list_size 0 -hls_segment_filename \"{outputPath}%03d.ts\" \"{outputPath}.m3u8\"";
    
                var process = new Process
                {
                    StartInfo = new ProcessStartInfo
                    {
                        FileName = "ffmpeg",
                        Arguments = arguments,
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        UseShellExecute = false,
                        CreateNoWindow = true,
                    }
                };
    
                process.Start();
                process.WaitForExit();
            }
        }
    }
    
    

    2.Create the VideoUploadModel.cs.

    namespace AspCore7_Web_Identity.Models
    {
        public class VideoUploadModel
        {
            public IFormFile? File { get; set; }
        }
    }
    
    

    3.Create Video folder under the Views folder. And create Index.cshtml and Upload.cshtml.

    @{
        ViewData["Title"] = "Video Playback";
    }
    
    <!-- Video.js CSS -->
    <link href="https://vjs.zencdn.net/7.8.4/video-js.css" rel="stylesheet">
    
    <!-- Your view content starts here -->
    <div class="container">
        <h2>Video Playback using HLS</h2>
        <div>
            <video id="my-video" class="video-js vjs-default-skin" controls preload="auto" width="640" height="360" data-setup='{}'>
                <source src="/uploads/hls/Trucks for children kids. Construction game_ Crawler excavator.mp4/Trucks for children kids. Construction game_ Crawler excavator.m3u8" type="application/x-mpegURL">
                Your browser does not support the video tag.
            </video>
        </div>
    </div>
    
    <!-- Video.js JS and HLS plugin -->
    <script src="https://vjs.zencdn.net/7.8.4/video.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/videojs-contrib-hls@5.15.0/dist/videojs-contrib-hls.js"></script>
    
    <!-- Initialize Video.js -->
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var player = videojs('my-video');
            player.play();
        });
    </script>
    
    
    
    @{
        ViewData["Title"] = "Upload Video";
    }
    
    <h2>Upload Video</h2>
    
    <form method="post" enctype="multipart/form-data"  action="upload">
        <div class="form-group">
            <label for="videoFile">Choose video to upload:</label>
            <input type="file" id="videoFile" name="File" class="form-control-file" required />
        </div>
    
        <button type="submit" class="btn btn-primary">Upload</button>
    </form>
    
    <!-- Optional: Show messages for success or error after upload -->
    @if (ViewBag.Message != null)
    {
        <div class="mt-4 alert @ViewBag.AlertClass">
            @ViewBag.Message
        </div>
    }
    
    
    1. Add Cors for static files, and Add MIME type in asp.net core.
                var builder = WebApplication.CreateBuilder(args);
                ...
                builder.Services.AddCors(options => options.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyMethod().AllowAnyOrigin()
                        //.SetIsOriginAllowed(_ => true)
                        .AllowAnyHeader();
                       //.AllowCredentials();
                }));
                ...
                // Support large files uploads.
                builder.Services.Configure<FormOptions>(options =>
                {
                    options.ValueLengthLimit = int.MaxValue;
                    options.MultipartBodyLengthLimit = int.MaxValue;
                    options.MultipartHeadersLengthLimit = int.MaxValue; 
                });
    
                ...
                builder.Services.AddControllersWithViews();
                var app = builder.Build();
                app.UseWhen(context => context.Request.Path.StartsWithSegments("/uploads"), appBuilder =>
                {
                    appBuilder.UseCors("CorsPolicy");
    
                    var provider = new FileExtensionContentTypeProvider();
                    // Add new mappings
                    provider.Mappings[".m3u8"] = "application/x-mpegURL";
                    provider.Mappings[".ts"] = "video/MP2T";
    
                    appBuilder.UseStaticFiles(new StaticFileOptions
                    {
                        ContentTypeProvider = provider,
                        FileProvider = new PhysicalFileProvider(Path.Combine(builder.Environment.WebRootPath, "uploads")),
                        RequestPath = "/uploads"
                    });
                });
                ...
                app.UseRouting();
    
                app.UseCors("CorsPolicy");
    
                app.UseAuthentication();
                app.UseAuthorization();
    
                app.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
                ...
    

    5.Download ffmpeg or other tools which can slice the video to many videos. And don't forget to add the ffmpeg to environment variable.

    User's image

    6.We also need add maxAllowedContentLength in web.config

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <system.webServer>
        <security>
          <requestFiltering>
            <!-- 1 GB -->
            <requestLimits maxAllowedContentLength="1073741824" />
          </requestFiltering>
        </security>
      </system.webServer>
    </configuration>
    

    7.The structure of my project.
    User's image

    8.Then we can play the video. Check the test result. We also could use other tools to play it online.

    BlazorApp1


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Jason Pan


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.