Search code examples
c#xamarinxamarin.formsxamarin-community-toolkit

Xamarin Community Toolkit MediaPlayer AutoPlay doesn't work?


I ran into this issue multiple times but until this current task that I'm doing it didn't worry me too much. But now I really need to remove autoplay because this audio must only play on user interaction and not at the beginning of the page load.

MediaPlayer CurrentState property and cannot be changed or assigned on screen loading because it is readonly. This is very annoying and IDK why it is not working. AutoPlay="false" and the sound still plays at the start of page loading.

My element is invisible due to it only having to play sound and no one needs to see it. If you have another way to do this please suggest in the comments and I will try.

<xct:MediaElement x:Name="mediaPlayer"
                  Source="{Binding WordSoundSource}"
                  IsVisible="false"
                  AutoPlay="false"/>

Update
If I add in my constructor mediaPlayer.Stop() to stop the element from playing at the start then on the play event of a user tapping nothing plays this is extremely annoying.

This is how I handle the mediaPlayer.Play() on user tapping an image which has Image.GestureRecognizers && TapGestureRecognizer

<Image Source="sound_icon.png"
       VerticalOptions="CenterAndExpand" 
       HorizontalOptions="EndAndExpand"
       HeightRequest="40"
       WidthRequest="40"
       Margin="0, 10, 80, 0">
           <Image.GestureRecognizers>
               <TapGestureRecognizer x:Name="ReplaySound"
                                     NumberOfTapsRequired="1"
                                     Tapped="ReplaySound_Tapped"/>
           </Image.GestureRecognizers>
</Image>
private void ReplaySound_Tapped(object sender, EventArgs e)
{
    if (mediaPlayer.CurrentState == MediaElementState.Stopped || 
       mediaPlayer.CurrentState == MediaElementState.Paused)
    {
        mediaPlayer.Play();
    }
}

There is also a post issues #1715 on GitHub about this being a bug, but it's almost a year ago... Am I wondering if this is the same thing?

Thanks in advance.


Solution

  • I had this issue last year the only possible way to solve it is setting Speed to 0 by default and then setting it to 1 when you need to play.

    <MediaElement 
           x:Name ="vidPlayer"
           Source="ms-appx:///XamarinForms101UsingEmbeddedImages.mp4"
           Speed="0"   
           ShowsPlaybackControls="True"
           .
           . 
           .
            />
    

    and then Change it to 1 when you play:

    vidPlayer.Speed= 1.0;