Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play sound on the client in Blazor?

I have a server-hosted Blazor application, and I'm trying to figure out how to play a sound on the client side when clicking a button (without touching JavaScript, ugh).

What I've tried:

@page "/"

<h1>Hello, world!</h1>

<audio src="alert.wav"></audio>
<button @onclick="@btnAlarm_handleClick">ALARM</button>

@code {

   void btnAlarm_handleClick()
   {
      // ???
   }
}

like image 209
Tomy Avatar asked Nov 29 '22 21:11

Tomy


1 Answers

Audio is pretty easy without JSInterop in Blazor.

Because Blazor controls elements in the DOM, we can just tell it to switch between two different audio elements, one set to play and one set not to play.

Use your own sound file 😀

Just in case you are concerned that this might download the audio file each time, don't - it doesn't.

Also, although this involves a round trip to the server, the traffic totals just around 770 Bytes for one round trip.

<h1>Play sound!</h1>

@code
{
    bool hidden = true;
}

<div class="card">
    <div class="card-header">
        <button @onclick=@(()=>hidden=!hidden)>@(hidden ? "Play" : "Stop")</button>

    </div>
    <div class="card-body">
        @if (!hidden)
        {
            <audio autoplay controls><source src="/crooner2.mp3" /></audio>
        }
        else
        {
            <audio controls muted><source src="/crooner2.mp3" /></audio>
        }
    </div>
</div>
like image 56
Mister Magoo Avatar answered Dec 09 '22 20:12

Mister Magoo