In my .NET MAUI Application, I need to implement an audio progress slider similar to the one shown in the attached image.
Image:
The progress bar should:
Fill dynamically as the audio plays.
Pause the progress when the audio is paused
Sync with the current playback position of the audio.
I am using toolkit:MediaElement to play the audio. How can I achieve this functionality in .NET MAUI?
Environment:
.NET MAUI Version: .NET 8
.NET MAUI Community Toolkit Version: "6.1.0"
CommunityToolkit.Maui.MediaElement Version: "2.0.0"
Platform: Android and iOS
Slider maximum value we need to set based on the audio file duration like below:
<Slider
x:Name="audioSlider"
Grid.Row="0"
Minimum="0"
VerticalOptions="Center"
HorizontalOptions="Fill"
ThumbColor="Transparent"
MaximumTrackColor="Gray"
MinimumTrackColor="White"
InputTransparent="True"
Maximum="{Binding Source={x:Reference MymediaElement}, Path=Duration.TotalSeconds}"
Value="{Binding Source={x:Reference MymediaElement}, Path=Position.TotalSeconds, Mode=OneWay}">
<Slider.WidthRequest>
<OnIdiom x:TypeArguments="x:Double">
<OnIdiom.Phone>400</OnIdiom.Phone>
<OnIdiom.Tablet>980</OnIdiom.Tablet>
<OnIdiom.Desktop>400</OnIdiom.Desktop>
</OnIdiom>
</Slider.WidthRequest>
</Slider>
Then Initialize the Timer like below:
private IDispatcherTimer timer;
// Initialize Timer
timer = Application.Current.Dispatcher.CreateTimer();
timer.Interval = TimeSpan.FromMilliseconds(500);
timer.Tick += (s, e) => UpdateSlider();
When we start playing the audio update the slider like below:
private void UpdateSlider()
{
try
{
if (MymediaElement != null && MymediaElement.Duration != null)
{
if (MymediaElement.Duration != null)
{
audioSlider.Maximum = MymediaElement.Duration.TotalSeconds;
}
audioSlider.Value = MymediaElement.Position.TotalSeconds;
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("DRAudioUpdateSliderException:>" + ex);
}
}
Added the MediaElement from code behind like below:
public static MediaElement MymediaElement;
MymediaElement = new MediaElement();
MymediaElement.WidthRequest = 1;
MymediaElement.HeightRequest = 1;
MymediaElement.ShouldAutoPlay = false;
MymediaElement.Source = audioUrl;
myGrid.Add(MymediaElement);