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

dg2k 1,396 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?

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,403 questions
C#
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.
10,834 questions
{count} votes

Accepted answer
  1. Yonglun Liu (Shanghai Wicresoft Co,.Ltd.) 41,926 Reputation points Microsoft Vendor
    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 Answers by the question author, which helps users to know the answer solved the author's problem.