Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Streaming video files in asp.net core 2

I want to play video in browser using asp.net core

in html I have

<video width="320" height="240" controls>
 <source src="http://localhost:55193/api/VideoPlayer/Download" type="video/mp4">
 Your browser does not support the video tag.
</video>

and in asp.net core 2

    [HttpGet]
    [Route("Download")]
    public async Task<IActionResult> Download()
    {
        var path = @"d:\test\somemovie.mp4";
        var memory = new MemoryStream();
        using (var stream = new FileStream(@"d:\test\somemovie.mp4", FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 65536, FileOptions.Asynchronous | FileOptions.SequentialScan))
        {
            await stream.CopyToAsync(memory);
        }
        memory.Position = 0;
        return File(memory, "application/octet-stream", Path.GetFileName(path));
    }

Does this code play file by streaming( I mean buffer file chunk by chunk and play)?

And if I want to play file from any position which user set the player's progress, How I can do it?

like image 605
unos baghaii Avatar asked Jul 14 '18 11:07

unos baghaii


2 Answers

Just use the normal return PhysicalFile here:

public class HomeController : Controller
    {
        public IActionResult Download()
        {
            return PhysicalFile(@"d:\test\somemovie.mp4", "application/octet-stream");
        }

Because it supports range headers which are necessary for streaming and resuming a file download: enter image description here

Also return File, FileStreamResult and VirtualFileResult support partial range requests too. Even static files middleware supports that too.

like image 120
VahidN Avatar answered Sep 23 '22 05:09

VahidN


Something is wrong. My sample doesn't support resume

    [HttpGet]
    [Route("Download2")]
    public IActionResult Download2()
    {
        return PhysicalFile(@"d:\test\somemovie.mp4", "application/octet-stream");
    }

enter image description here

and there is no accept-ranges in response headers

enter image description here

but when I use

[HttpGet]
    [Route("Download")]
    public async Task<IActionResult> Download()
    {
        var path = @"d:\test\somemovie.mp4";
        var memory = new MemoryStream();
        using (var stream = new FileStream(@"d:\test\somemovie.mp4", FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 65536, FileOptions.Asynchronous | FileOptions.SequentialScan))
        {
            await stream.CopyToAsync(memory);
        }
        memory.Position = 0;
        return File(memory, "application/octet-stream", Path.GetFileName(path),true); //enableRangeProcessing = true
    }

with "enableRangeProcessing" parameter true

enter image description here

Can you provide more explanation why the case is this? And which solution I should use? I got confused.

like image 45
unos baghaii Avatar answered Sep 22 '22 05:09

unos baghaii