.netmauimediaelement

Using .Net Maui CommunityToolkit MediaElement to Play Short Sound Fx


I'm trying to play "different sound effects", basically, using a hidden MediaElement. My current approach assumes I've already declared a named MediaElement in the xaml markup for a page (call it "FxPlayer") with PlaybackControls set to hidden, something like:

<toolkit:MediaElement x:Name="FxPlayer" MaximumHeightRequest="1" MaximumWidthRequest="1" ShouldShowPlaybackControls="False" />

And that everything else happens in code behind, including:

I know there will be latency and am not looking to sync to visual action, so the "fx" label is a bit strong, but gets to the point. Need an "audio channel out".

Thanks in advance, as always. (related prior post)


Solution

  • Maybe this helps you. I use this code in a Code behind and Trigger it over WeakReferenzMessenger. Code in the Constructor of my Page:

    WeakReferenceMessenger.Default.Register<PlaySoundMessage>(this, (r, m) =>
    {
        MainThread.BeginInvokeOnMainThread(() => {
            this.PlaySound(m.Value);
        });
    });
    

    Code of the Method:

    void PlaySound(string soundname)
    {
        if (!soundname.IsNullOrEmpty())
        {
            mediaElement.Source = MediaSource.FromResource(soundname);
            mediaElement.Stop();
            mediaElement.Play();
        }
    
    }