这是音频播放器的源代码:
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 不适合播放不同类型的音频文件。请提出替代方案。