0

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()
   {
      // ???
   }
}

  • 1
    You mean, play a sound on the browser? Which means executing Javascript – Panagiotis Kanavos Jan 31 at 15:16
  • C# is on server Side, Javascript is on client side. What you will do is play your sound inside your data center :p – pix Jan 31 at 15:16
  • Did not know :) – pix Jan 31 at 15:18
  • @PanagiotisKanavos Yes, in the browser. I was hoping to keep the application pure c#, without introducing javascript in the mix – Tomy Jan 31 at 15:18
  • @Tomy what you ask is how to call the play() method on the audio element. ASP.NET Core Blazor JavaScript interop explains how to call Javascript methods in general. Seriously though, there's no reason to go to the server only to come back to the browser and call that method. – Panagiotis Kanavos Jan 31 at 15:20
8

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>
  • Not tested in Safari - because I don't do Apple. – Mister Magoo Feb 1 at 16:09
1

In this scenario, the only way to tell the <audio> element to start playing is ultimately ... through Javascript.

There are two ways; simple, and not-quite-so-simple.

(1) The simple way, using inline JS:

<audio id="sound" src="/media/alert.wav" />

<button onclick="document.getElementById('sound').play()">Play through Javascript</button>

(2) The not-quite-so-simple way, by triggering an event through SignalR on the server application, which then through SignalR sends back a command to invoke a JS function, which you need to have created beforehand in a particular way:

<audio id="sound" src="/media/alert.wav" />

<button @onclick="@ClickHandler">Play through C#</button>

@code {
    async void ClickHandler()
    {
        await JSRuntime.InvokeAsync<string>("PlaySound"); // this calls "window.PlaySound()"
    }
}

Also create this file: /js/PlaySound.js

window.PlaySound = function() {
  document.getElementById('sound').play();
}

Also edit this file: /Pages/_Host.cshtml

<head>
    <!-- Various other tags -->
    <script src="/js/PlaySound.js"></script>
</head>

Bottom line:

  • Accept that you will need Javascript to do things like this.
  • Don't bother using Blazor to call JS, unless you absolutely need Server Side stuff to determine if the Javascript code is going to be called and/or how.
1

I did something similar, but used src:

Sample from .Net user group demo, dropdown of mp3's to select from.

@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment env
@inject AppState State

<h3>Media</h3>

<select @onchange="PlayFile" value="@State.LastSong">
    @foreach (var f in new System.IO.DirectoryInfo(env.WebRootPath + "/sounds").GetFiles("*.mp3"))
    {
        <option value="/sounds/@f.Name">@f.Name</option>
    }
</select>

<audio src="@_currentFile" autoplay></audio>

@code {

    private string _currentFile = "";

    private void PlayFile(ChangeEventArgs e)
    {
        var song = e.Value.ToString();

        _currentFile = song;
        State.SetSong(song);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.