Can the CommunityToolkit.Maui.MediaElement be used in Code-behind?

dg2k 1,416 Reputation points
2023-03-23T15:15:37.37+00:00

I can use the CommunityToolkit.Maui.MediaElement to play an audio file in XAML. I understand this control can also play video but my need is just to provide an audio prompt from within a code behind. I tried the following which compiles okay, but nothing happens.

MediaElement mediaPlayer;

mediaPlayer ??= new MediaElement()
{
	Speed = 1,
	Source = MediaSource.FromResource("Alert.mp3"),   /* Resouces\Raw\Alert.mp3 */
	ShouldAutoPlay = false,
	ShouldShowPlaybackControls = false,
	ShouldMute = false,
	Volume = 0.95
};

mediaPlayer.Play();

If mediaPlayer object is instead in XAML, everything works as expected. MediaElement doesn't seem to like the object being created in code-behind.

Am I using it wrongly or there is a workaround for this?

Developer technologies | .NET | .NET MAUI
Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
{count} votes

Answer accepted by question author
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 50,156 Reputation points Microsoft External Staff
    2023-03-24T03:04:57.76+00:00

    Hello,

    MediaElement is a page control that must be on the page to function.

    If you don't want to declare MediaElement in xaml, you could refer to the following code:

    //in xaml
    <VerticalStackLayout x:Name="myStack"
    	...
    </VerticalStackLayout>
    
    // code-behind
    MediaElement mediaPlayer;
    mediaPlayer = new MediaElement()
    {
        Speed = 1,
                IsVisible = false,
                Source = MediaSource.FromResource("alert.mp3"),   /* Resouces\Raw\Alert.mp3 */
                ShouldAutoPlay = false,
                ShouldShowPlaybackControls = false,
                ShouldMute = false,
                Volume = 0.95
            };
    myStack.Add(mediaPlayer);
    mediaPlayer.Play();
    myStack.Remove(mediaPlayer);
    

    Best Regards,

    Alec Liu.


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.