Blazor Sound Boared

 




This is a cute little application that will allow the user to click a button and play a sound in a Blazor application.

How it works

We started with the 6 sounds, see image.  We added those mp3 files to our web application so we can access them from the application.

We generated a list of the names of the sounds we will be supporting:

    List<string> sounds = new List<string>()
    {
        "applause", "boo", "gasp", "tada", "victory", "wrong"
    };

HTML Tags

For this application we will need an audio tag for each sound and a button for each sound:


    <audio id="boo" src="/sounds/boo.mp3"></audio>

For the button:

        <button type="button" 
            Boo
         </button>

Normally we would have 6 each of these tags, but with Blazor we can do a couple of for loops, We'll need a method to build the path for the mp3 file.

    @foreach (var s in sounds)
    {
        <audio id="@s" src="@GetSoundFile(@s)"></audio>
    }

Buttons:
    @foreach (var s in sounds)
    {
        <button type="button" 
            @s
         </button>
    }


Play the sound

We will need to play the sound when the button is clicked.  To do this we will need to add an onclick event.  

    onclick="document.getElementById('@s').play()"

If you noticed we are assigning the ID of the audio tag with the name of the sound.  This allows us to get the element by ID in the click event.

Stop Playing


We will want the sound to stop playing if the user leaves the area of the sound button.  We can do this by adding an onblur event to the button:

    onblur="document.getElementById('@s').pause()" class="btn"


If we run the application at this point, we will see 6 buttons.  When the user clicks on a button they will hear the sound associated with the button.  Once they leave the focus of the button, the sounds will stop.

Even at this point, the app is pretty cool.  But let's see if we can make it a little better.

Make Pretty

Our buttons are styled like normal buttons, we can make them look nicer.  After a little image search, I found six nice button images.  I used an image editor created an image file, and saved it with the sound name in the image folder of the application.  

I now need a method to build the image path just like the mp3 path.  Once I created that, I added the new style to the button definition in the for loop.

        style="background-image:url(@GetButton(@s))

This returns the string /images/boo.png to provide the image source for the button.

See the live demo

Summary

The goal was to create a fun little Blazor application that played sounds.  I think we were able to do that and made it pretty nice in the process.


Comments

Popular posts from this blog

Yes, Blazor Server can scale!

Blazor new and improved Search Box

Blazor Wizard Step Component