My question: How can I correctly instantiate a MediaSource instance and/or the MediaElement using code behind so that I can:
I'm planning to hide the control as I just want to be able to selectively play short sound "effects" without a player control visible. But first....
WelcomeVoicePlayer is a named MediaElement in the PageContent xaml. I'm trying to use that element to play a sound that I set at runtime and/or change at runtime in the ContentPage code.
Approach that's not working:
// Neither of these approaches to setting Source worked...
var voiceFile = FileMediaSource.FromFile(tempVoicePath);
//WelcomeVoicePlayer = new MediaElement { Source = voiceFile };
// When Play is called I hear nothing, even though audio file is good etc...
WelcomeVoicePlayer.Play();
Happy to reinstantiate the control if needed for each new source, but still need to able to set Source from code.
Any clues appreciated.
Dave G
P.S. Big thanks to all those that brought the MediaElement forward to Maui!
I think your first option is pretty close. You might want to try this:
var voiceFile = MediaSource.FromFile(tempVoicePath);
WelcomeVoicePlayer = new MediaElement { Source = voiceFile };
A full example, that I have seen working myself just now is this:
var page = new ContentPage();
var stack = new VerticalStackLayout();
var mediaElement = new MediaElement
{
ShouldAutoPlay = true,
Source = MediaSource.FromFile("C:\\Users\\jfversluis\\Desktop\\video.mp4"),
};
stack.Children.Add(mediaElement);
page.Content = stack;
MainPage = page;
The one thing I would note is that filesystem access is pretty straight-forward on Windows and macOS, but on the mobile devices it might not be. There is more things to deal with like permissions or maybe files that are loaded from a cloud-provider and first need to be downloaded.
If something is not working you might want to hook up the MediaFailed
event to get some more details on what is going wrong.
P.S. Big thanks to all those that brought the MediaElement forward to Maui!
You're welcome!