使用MediaElement的WPF音频播放器有时会滞后

时间:2013-09-16 15:21:09

标签: c# wpf

这是音频播放器的源代码:

public partial class MainWindow : Window
{
    private DispatcherTimer timer;

    public MainWindow()
    {
        InitializeComponent();
        mPlayer.LoadedBehavior = MediaState.Manual;
        mPlayer.UnloadedBehavior = MediaState.Manual;
        timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromMilliseconds(500);
        timer.Tick += timer_Tick;
        mPlayer.MediaOpened += mPlayer_MediaOpened;
    }

    void mPlayer_MediaOpened(object sender, RoutedEventArgs e)
    {
            TimeSpan ts = mPlayer.NaturalDuration.TimeSpan;
            SeekSlider.Maximum = ts.TotalSeconds;
    }

    void timer_Tick(object sender, EventArgs e)
    {
            SeekSlider.Value = mPlayer.Position.TotalSeconds;

    }

    private MediaElement mPlayer = new MediaElement();

    private void ButtonOpen_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            var ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == true)
            {
                timer.Start();
                mPlayer.Source = new Uri(ofd.FileName);
                mPlayer.Volume = VolumeSlider.Value;
                timer.Start();
                mPlayer.Play();
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine(ex.Message);
        }
    }

    private void ButtonPlay_Click(object sender, RoutedEventArgs e)
    {
        mPlayer.Play();
        timer.Start();
    }

    private void ButtonPause_Click(object sender, RoutedEventArgs e)
    {
        mPlayer.Pause();
        timer.Stop();
    }

    private void ButtonStop_OnClick(object sender, RoutedEventArgs e)
    {
        timer.Stop();
        mPlayer.Stop();
    }

    private void SeekSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {
            mPlayer.Position = TimeSpan.FromSeconds(SeekSlider.Value);
    }


    private void VolumeSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
    {
            mPlayer.Volume = VolumeSlider.Value;
    }
}

我不知道它为什么会突然滞后。请帮我找到问题所在。 如果您认为MediaElement不适合播放不同类型的音频文件。请提出替代方案。

1 个答案:

答案 0 :(得分:3)

SeekSlider_ValueChanged事件经常被解雇。所以这导致了一些滞后。

所以我使用Thumb.DragCompleted事件解决了这个问题。在此之后,播放非常流畅。