MediaElement not playing next audio file after it stops
See original GitHub issueIs there an existing issue for this?
- I have searched the existing issues
Did you read the “Reporting a bug” section on Contributing file?
- I have read the “Reporting a bug” section on Contributing file: https://github.com/CommunityToolkit/Maui/blob/main/CONTRIBUTING.md#reporting-a-bug
Current Behavior
When MediaElement stopped playing the firs mp3 file I triggered a an event and changed the source to the next mp3 file, but not starting to play it. I posted a problem here. After the MediaElement source has changed I called the Play() function, but nothing.
Expected Behavior
Would be nice to auto play the song when the source changed.
Steps To Reproduce
public partial class AudioPlayer : ContentView
{
public static readonly BindableProperty SourceProperty = BindableProperty.Create(nameof(Source), typeof(MediaSource), typeof(AudioPlayer), null);
public MediaSource Source
{
get => (MediaSource)GetValue(SourceProperty);
set => SetValue(SourceProperty, value);
}
public AudioPlayer()
{
InitializeComponent();
BindingContext = this;
mediaElement.PropertyChanged += OnPropertyChanged;
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == MediaElement.DurationProperty.PropertyName)
{
positionSlider.Maximum = mediaElement.Duration.TotalSeconds;
}
}
private void OnMediaOpened(object sender, EventArgs e)
{ }
private void OnStateChanged(object sender, MediaStateChangedEventArgs e)
{ }
private void OnMediaFailed(object sender, MediaFailedEventArgs e)
{ }
private void OnMediaEnded(object sender, EventArgs e)
{
eventManager.HandleEvent(this, EventArgs.Empty, "MediaEnded");
mediaElement.Play();
}
private void OnPositionChanged(object sender, MediaPositionChangedEventArgs e)
{
positionSlider.Value = e.Position.TotalSeconds;
}
private void OnSeekCompleted(object sender, EventArgs e)
{ }
private void OnPlayClicked(object sender, EventArgs e)
{
mediaElement.Play();
}
private void OnPauseClicked(object sender, EventArgs e)
{
mediaElement.Pause();
}
private void OnStopClicked(object sender, EventArgs e)
{
mediaElement.Stop();
}
private void OnMuteClicked(object sender, EventArgs e)
{
mediaElement.ShouldMute = !mediaElement.ShouldMute;
}
private void OnUnloaded(object sender, EventArgs e)
{
// Stop and cleanup MediaElement when we navigate away
mediaElement.Handler?.DisconnectHandler();
}
private void OnSliderDragCompleted(object sender, EventArgs e)
{
ArgumentNullException.ThrowIfNull(sender);
var newValue = ((Slider)sender).Value;
mediaElement.SeekTo(TimeSpan.FromSeconds(newValue));
mediaElement.Play();
}
private void OnSliderDragStarted(object sender, EventArgs e)
{
mediaElement.Pause();
}
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
xmlns:converters="clr-namespace:Solution.MobileApp.Converters"
x:Class="Solution.MobileApp.Components.AudioPlayer"
Unloaded="OnUnloaded">
<ContentView.Resources>
<toolkit:TimeSpanToSecondsConverter x:Key="TimeSpanConverter" />
<converters:SecondsToStringConverter x:Key="SecondsToStringConverter" />
</ContentView.Resources>
<ScrollView>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<toolkit:MediaElement
Grid.Row="0"
x:Name="mediaElement"
ShouldAutoPlay="True"
Source="{Binding Source}"
MediaEnded="OnMediaEnded"
MediaFailed="OnMediaFailed"
MediaOpened="OnMediaOpened"
PositionChanged="OnPositionChanged"
StateChanged="OnStateChanged"
SeekCompleted="OnSeekCompleted"/>
<HorizontalStackLayout Grid.Row="1" Padding="0,0,0,15">
<Label HorizontalOptions="Center">
<Label.Text>
<MultiBinding StringFormat="Current State: {0}">
<Binding Path="CurrentState" Source="{x:Reference mediaElement}" />
</MultiBinding>
</Label.Text>
</Label>
</HorizontalStackLayout>
<Grid Grid.Row="2" Padding="0,10,0,10" ColumnDefinitions="*,*,*,*" ColumnSpacing="5">
<Button Grid.Column="0" Text="Play" Clicked="OnPlayClicked" />
<Button Grid.Column="1" Text="Pause" Clicked="OnPauseClicked" />
<Button Grid.Column="2" Text="Stop" Clicked="OnStopClicked" />
<Button Grid.Column="3" Text="Mute" Clicked="OnMuteClicked">
<Button.Triggers>
<DataTrigger TargetType="Button"
Binding="{Binding ShouldMute, Source={x:Reference mediaElement}}"
Value="True">
<Setter Property="Text" Value="Unmute" />
</DataTrigger>
<DataTrigger TargetType="Button"
Binding="{Binding ShouldMute, Source={x:Reference mediaElement}}"
Value="False">
<Setter Property="Text" Value="Mute" />
</DataTrigger>
</Button.Triggers>
</Button>
</Grid>
<VerticalStackLayout Grid.Row="3" Padding="0,10,0,10">
<Slider x:Name="positionSlider"
MinimumTrackColor="Gray"
DragStarted="OnSliderDragStarted"
DragCompleted="OnSliderDragCompleted"/>
<HorizontalStackLayout Padding="0,10,0,10">
<Label HorizontalOptions="Center">
<Label.Text>
<MultiBinding StringFormat="{}Position: {0}/{1}">
<Binding Path="Position" Source="{x:Reference mediaElement}" Converter="{StaticResource SecondsToStringConverter}" />
<Binding Path="Duration" Source="{x:Reference mediaElement}" Converter="{StaticResource SecondsToStringConverter}" />
</MultiBinding>
</Label.Text>
</Label>
</HorizontalStackLayout>
</VerticalStackLayout>
<HorizontalStackLayout Grid.Row="4" Padding="0,10,0,10">
<Label>
<Label.FormattedText>
<FormattedString>
<Span Text="Volume:" />
<Span Text="{Binding Source={x:Reference mediaElement}, Path=Volume, StringFormat='{}{0:P0}'}" />
</FormattedString>
</Label.FormattedText>
</Label>
<Slider Maximum="1.0"
Minimum="0.0"
MinimumTrackColor="Red"
MaximumTrackColor="Gray"
Margin="10,0,10,0"
WidthRequest="300">
<Slider.Value>
<Binding Path="Volume" Source="{x:Reference mediaElement}" />
</Slider.Value>
</Slider>
</HorizontalStackLayout>
</Grid>
</ScrollView>
</ContentView>
<?xml version="1.0" encoding="utf-8" ?>
<pages:BasePage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:pages="clr-namespace:Solution.MobileApp.Pages"
xmlns:views="clr-namespace:Solution.MobileApp.Pages.Tabs"
xmlns:component="clr-namespace:Solution.MobileApp.Components"
xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
xmlns:viewModels="clr-namespace:Solution.MobileApp.ViewModels"
x:TypeArguments="viewModels:MusicPageViewModel"
x:DataType="viewModels:MusicPageViewModel"
x:Class="Solution.MobileApp.Pages.Tabs.MusicPage"
Title="MediaElement">
<VerticalStackLayout>
<Label Text="Welcome to PLAYLIST PAGE!"
VerticalOptions="Center"
HorizontalOptions="Center" />
<component:AudioPlayer x:Name="audioPlayer" />
</VerticalStackLayout>
</pages:BasePage>
public partial class MusicPageViewModel : BaseViewModel
{
[ObservableProperty]
private MediaSource source;
private List<string> songs = new List<string>
{
"Mostantol.mp3",
"Vihar.mp3"
};
public MusicPageViewModel()
{
source = MediaSource.FromResource(songs[0]);
}
public string NextSong() => songs[1];
}
public partial class MusicPage : BasePage<MusicPageViewModel>
{
private readonly ILogger logger;
public MusicPage(MusicPageViewModel viewModel, ILogger<MusicPage> logger) : base(viewModel)
{
this.logger = logger;
InitializeComponent();
audioPlayer.Source = viewModel.Source;
}
public void OnMediaEnded(object sender, EventArgs e)
{
audioPlayer.Source = BindingContext.NextSong();
}
}
Link to public reproduction project repository
Environment
- .NET MAUI CommunityToolkit: 5
- OS: Win 11
- .NET MAUI: 1
Anything else?
no
Issue Analytics
- State:
- Created 6 months ago
- Comments:8 (5 by maintainers)
Top Results From Across the Web
wpf - After playing a MediaElement, how can I play it again?
I found it, you just have to stop the audio first, then set the position: TestAudio.Stop(); TestAudio.Position = TimeSpan.Zero;.
Read more >Playing sound using WPF MediaElement does not work ...
We have a WPF software running on Windows 10 LTSB 64 bit (1607). In order to play a sound file, we use System.Windows.Media....
Read more >SL12: Pausing, Stopping, or Playing Media in Silverlight ...
The controls enable users to pause or stop the video to prevent the video images on the MediaElement surface from moving, and stop...
Read more >HTMLMediaElement - Web APIs | MDN
Chrome Edge
HTMLMediaElement Full support. Chrome3. Toggle history Full support. Edge12. T...
abort event Full support. Chrome3. Toggle history Full support. Edge12. T...
addTextTrack Full support....
Read more >Introducing MediaElement for .NET MAUI - YouTube
With MediaElement you are now able to easily play video and audio from ... Live Demo 9:53 - Play Video From Embedded Resources...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
A solution uploaded to an open GitHub repository is the best option please. Happy to assist with any questions around that if you have any
We haven’t received a reproduction sample from you. The issue is closed.