I came across a problem the other day where I needed to play a sound file in a Blazor WebAssembly application, but there were very limited resources as to how to do this. So, once I figured it out, I also figured that someone else was going to have this problem.

(Even if that person is just me in the future).

Let’s see how to play a sound in Blazor!

The Sample Project

As always, there’s a sample project on GitHub that has the code we’re going to write in this post. Check it out!

The Steps

There are five steps we need the ability to play a sound in Blazor:

  1. An HTML <audio> element.
  2. A JavaScript method to play the audio.
  3. An instance of IJSRuntime injected to our Blazor component.
  4. A C## method that uses IJSRuntime to invoke the JavaScript method.
  5. An HTML element that invokes the C## method when clicked.

#blazor #javascript #webassembly #programming

How to Play a Sound with Blazor and JavaScript
6.35 GEEK