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()
{
// ???
}
}
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With