简体   繁体   English

C# 如何将进度条与音频播放结合起来?

[英]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? C# 如何将进度条与音频播放结合起来?

You could use SMTC directly that contains progress.您可以直接使用包含进度的SMTC

<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.对于服装进度,我们需要获取媒体文件的时长和当前音乐 position。

We could get the music duration with MediaOpened event.我们可以通过MediaOpened事件获取音乐持续时间。

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.然后我们需要在媒体PositionChanged事件中计算进度条的值(最大值为 100)。

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;

    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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