How to Stop Previous Audio When Playing a New One in .NET MAUI

Sreejith Sreenivasan 941 Reputation points
2025-02-25T18:00:48.0266667+00:00

In my .NET MAUI application, I am using MediaElement from the .NET MAUI Community Toolkit and WebView to play audio files. However, I am facing an issue where if I play audio on one page, it continues playing even when I navigate to another page and play a different audio file. The previous audio does not stop or pause automatically, causing multiple audios to play simultaneously.

Expected Behavior:

If an audio file is currently playing and the user starts playing another audio on a different page, the previous audio should stop automatically before the new one starts.

XAML Code for MediaElement:

<toolkit:MediaElement
           HorizontalOptions="FillAndExpand" 
           IsVisible="True"
           x:Name="audioplayer">
           <toolkit:MediaElement.HeightRequest>
              <OnIdiom x:TypeArguments="x:Double">
                  <OnIdiom.Phone>180</OnIdiom.Phone>
                   <OnIdiom.Tablet>270</OnIdiom.Tablet>
                   <OnIdiom.Desktop>180</OnIdiom.Desktop>
              </OnIdiom>
           </toolkit:MediaElement.HeightRequest>
 </toolkit:MediaElement>

XAML Code for WebView:

<WebView
        x:Name="audio_webview" 
        BackgroundColor="Transparent" 
        Navigated="OnWebViewNavigated"
        HorizontalOptions="FillAndExpand"
        VerticalOptions="CenterAndExpand" >
        <WebView.HeightRequest>
            <OnIdiom x:TypeArguments="x:Double">
                <OnIdiom.Phone>80</OnIdiom.Phone>
                <OnIdiom.Tablet>120</OnIdiom.Tablet>
                <OnIdiom.Desktop>80</OnIdiom.Desktop>
            </OnIdiom>
        </WebView.HeightRequest>
        <WebView.WidthRequest>
            <OnIdiom x:TypeArguments="x:Double">
                <OnIdiom.Phone>420</OnIdiom.Phone>
                <OnIdiom.Tablet>630</OnIdiom.Tablet>
                <OnIdiom.Desktop>420</OnIdiom.Desktop>
            </OnIdiom>
        </WebView.WidthRequest>
 </WebView>

Environment:

.NET MAUI Version: .NET 8

.NET MAUI Community Toolkit Version: "6.1.0"

Platform: Android and iOS

How can I ensure that when a new audio file starts playing on a different page, any previously playing audio stops automatically?

.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,955 questions
{count} votes

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.