简体   繁体   中英

C# How to combine progress bar with audio playing?

I want to use a progress bar that could reflect the audio currently playing, ie the duration of the audio.

Below is a snippet of my program, it's setup to play an audio file on button click.

在此处输入图像描述

C# How to combine progress bar with audio playing?

You could use SMTC directly that contains progress.

<MediaPlayerElement
    x:Name="mediaPlayerElement"
    Margin="0,0,10,0"
    VerticalAlignment="Top"
    AreTransportControlsEnabled="True"
    />

For costuming progress, we need get the media file's duration and the current music position.

We could get the music duration with MediaOpened event.

private async void Player_MediaOpened(MediaPlayer sender, object args)
{
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
    {
        MusicTime = (int)sender.PlaybackSession.NaturalDuration.TotalSeconds();

    });
}

And then we need calculate the value of progress bar(the max value is 100) in media PositionChanged event.

private async void PlaybackSession_PositionChanged(MediaPlaybackSession sender, object args)
{
    await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
    {
        CurentPosition = (int)sender.Position.TotalSeconds;
        progressbar.Value = (CurentPosition / MusicTime) *100;

    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM