Search code examples
c#asp.net-coreaudiorazor-pages

In ASP.NET Core use audio control to play audio from hex string


I want to add an audio control to my ASP.NET Core code. When I set the source of the control to be a file it works.

Now I have the audio as a hex string that I retrieve from the database, and I want to send it to be the source of the audio control (without saving it to a file)

Here is my code:

<!DOCTYPE html>
<html>
<head>
    <title>Your Razor Page</title>
</head>
<body>
    <audio controls>
        <source id="audioSource" type="audio/mp3" />
    </audio>

    @* Include this section to set up the byte array and content type *@
    @section scripts
    {
        <script>
            var audioData = "@Html.Raw(Model.Base64AudioData)";
            var contentType = "@Model.ContentType";
            document.getElementById("audioSource").src = "data:" + contentType + ";base64," + audioData;

        </script>
    }
</body>
</html>

The cs file:

public string Base64AudioData { get; set; }

public string ContentType { get; set; }

public void OnGet()
{
    byte[] audioData = GetYourAudioByteArray();
    Base64AudioData = Convert.ToBase64String(audioData);
    ContentType = "audio/mp3"; // Set the correct content type based on your audio format
}

private byte[] GetYourAudioByteArray()
{

    string hexString = "FFF344C40012000DE0001806000000404010FC....."  

    byte[] byteArray = Enumerable.Range(0, hexString.Length)
                      .Where(x => x % 2 == 0)
                      .Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
                      .ToArray();

    return byteArray;
}

I see that Base64AudioData contains the correct string to play, still, it doesn't work and the audio control appears disabled.

Any idea why?


Solution

  • After testing, I found that the problem was in your script. During the test, I found that Html.Raw was not recognized (it may be related to my VS2022), so I modified the code in the simplest way, and it worked very well.

    You can change you code like below:

    @page "/mp3"
    @model BlazorApp5.Pages.mp3Model
    
    <!DOCTYPE html>
    <html>
    <head>
        <title>Your Razor Page</title>
    </head>
    <body>
        <audio controls>
            <source id="audioSource" type="audio/mp3" src="@($"data:{Model.ContentType};base64,{Model.Base64AudioData}")" />
        </audio>
    </body>
    </html>
    
    
    @{
    }
    

    Backend Code:

    enter image description here

    Test Result

    enter image description here