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:
Playing audio with the MediaElement when it's host page is active, but only in response to a message (using WeakReferenceMessages, say).
Using either a file or stream to set the Source of the existing FxPlayer when a message arrives to the page control. The sound the "FxPlayer" element plays changes depending on the message, which is why I assume a good implementation will let me use MediaSource instances created at runtime and used to set the Source element of the property whenever I want to play an "effect".
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)
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();
}
}