Hello,
I used MediaElement
to replace the webview to play audio.
As you mentioned, if you use MediaElement and audio will play twice in other pages. In your first page of application, you can create a static MediaElement with C# code. For example, if your first page is DailySaintPage.
I add a static MediaElement in the OnAppearing method And this MediaElement to the Gird(That I created in the following steps).
public static MediaElement MymediaElement;
protected override void OnAppearing()
{
base.OnAppearing();
MymediaElement = new MediaElement();
MymediaElement.WidthRequest = 1;
MymediaElement.HeightRequest = 1;
MymediaElement.ShouldAutoPlay = false;
myGrid.Add(MymediaElement);
}
And I create a Grid to wrap the Play button in the DailySaintPage.xaml layout.
<Grid Grid.Column="1" x:Name="myGrid">
<Image
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand"
Source="ic_audio_play_icon_xx.png">
<Image.GestureRecognizers>
<TapGestureRecognizer
Tapped="PlayAudio"
NumberOfTapsRequired="1">
</TapGestureRecognizer>
</Image.GestureRecognizers>
</Image>
</Grid>
In the PlayAudio event. Do not need to open a popup then play it. You can play it by following code directly.
public async void PlayAudio(object sender, EventArgs args)
{
try
{
if (!string.IsNullOrWhiteSpace(mAudioURL))
{
// await Application.Current.MainPage.ShowPopupAsync(new CatholicBrain.Daily_Activities.DailyAudioPopUpPage(mAudioURL));
// Debug.WriteLine("Finalaudioplay:>>" + mAudioURL);
MymediaElement.Source = mAudioURL;
MymediaElement.Play();
}
else
{
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Exception:>" + ex);
}
}
Then, if you want to stop the play the audio in the DailyReadingPage. You can control it by DailySaintPage.MymediaElement.Stop();
, play it by DailySaintPage.MymediaElement.Play();
private void Button_Clicked(object sender, EventArgs e)
{
DailySaintPage.MymediaElement.Stop();
//set the media resouces.
var mAudioURL = "Newaudio.mp3";
DailySaintPage.MymediaElement.Source = mAudioURL;
DailySaintPage.MymediaElement.Play();
}
Best Regards,
Leon Lu
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.