首页 > 解决方案 > 没有错误或异常,但代码不会在 WPF 应用程序中播放音频文件

问题描述

我使用此代码在用 C# 编写的 WPF 应用程序中播放音频 ( .wav) 文件。这是我播放音频文件的代码:

Uri uri = new Uri(@"C:\Users\naseem\source\repos\ChatBotAssistant\ChatBotAssistant\bin\Debug\Speech.wav");
MediaPlayer player = new MediaPlayer();
player.Open(uri);
player.Play();

没有错误也没有异常,但它不播放音频文件。

标签: c#wpfaudio

解决方案


MediaPlayer媒体文件无法打开时不会抛出异常。通常,您应该使用以下事件来规避MediaPlayer.

MediaOpened被触发时,您可以安全地调用Play,而当MediaFailed被触发时,您可以处理错误,因为那时没有加载媒体。将ExceptionEventArgs包含Exception发生的事情。

private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
   var uri = new Uri(@"C:\Users\naseem\source\repos\ChatBotAssistant\ChatBotAssistant\bin\Debug\Speech.wav");
   var player = new MediaPlayer();
   player.MediaOpened += OnMediaOpened;
   player.MediaFailed += OnMediaFailed;
   player.Open(uri);
}

private void OnMediaOpened(object sender, EventArgs e)
{
   var player = (MediaPlayer)sender;
   player.Play();
}

private void OnMediaFailed(object sender, ExceptionEventArgs e)
{
   var exception = e.ErrorException;
   // Handle exception
}

推荐阅读