Search code examples
c#asp.net-mvchtml5-audio

audio controls in MVC .net core 3.1


When I try to play a network recoding inside a razor page in an MVC .net core 3.1 page, the playback button is gray-out.

I am using Chrome 102.0, and all content is allowed for that page in the site settings.

Since I am debugging in visual studio the certificate is recognized as a secure connection.

Finally, the internal UNC path is valid, and if I place it in the browser address bar, the recording does play as expected.

Here is a sample of what the code looks like inside the razor page:

@page
@model TestStreamRecording.Pages.playerModel
@{
}


<audio controls src="\\server.local\shares\folderone\subfolder\vendor\sample.mp3"></audio>

Solution

  • The problem you have is you are trying to link the browser to physical file, while the browser attempt to access it as web resource.

    I can think of 2 options:

    1. Use Static files middleware and place the mp3 in the application wwwroot folder
    2. Create file stream end point

    Option 1 is easy, but you have to move the file to wwwroot folder, and it is static solution:

    In startup.cs ensure you have

    app.UseStaticFiles();
    

    Then simply move the audio file to wwwroot folder and in the view

    <audio controls>
        <source src='/audio.mp3' type="audio/mp3">
        Your browser does not support the audio element.
    </audio>
    

    audio.mp3 is sample file here


    Option 2 to stream the file:

    First create a stream endpoint in a controller

        public IActionResult Stream()
        {
            var path = "Your storage path here. ex :
    \\server.local\shares\folderone\subfolder\vendor\sample.mp3");
            var fs = new FileStream(path, FileMode.Open);
    
            return new FileStreamResult(fs, "audio/mp3")
            {
                EnableRangeProcessing = true,
            };
        }
    

    Link the audio player to the file

    <audio controls>
        <source src='/home/stream' type="audio/mp3">
        Your browser does not support the audio element.
    </audio>