c# - 没有错误或异常,但代码不会在 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();
没有错误也没有异常,但它不播放音频文件。
解决方案
MediaPlayer
媒体文件无法打开时不会抛出异常。通常,您应该使用以下事件来规避MediaPlayer
.
- MediaOpened - 打开媒体时发生。
- 媒体失败- 遇到错误时发生。
当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
}
推荐阅读
- vue.js - 电容离子4 vue项目网::ERR_FILE_NOT_FOUND
- sql - 如何将 SQL Server 查询限制为单个表分区
- google-apps-script - 如何使用 Google API 将 Google Sheet 部署为 Web 应用程序
- qt - 我有一个可以向上移动线条的 onclick 按钮,如何让线条在达到某个 x、y 值后不向上移动?
- python - 如何根据用户在哪个适配器上的输入更改网络适配器设置?
- x11 - X11 客户端设置 _NET_WM_STATE_DEMANDS_ATTENTION 时未收到事件
- node.js - 有时,Heroku 显示我的 Express.js 应用程序的应用程序错误
- delphi - 选择包含在祖先中引入的组件
- python - “PlayerStatsForm”对象没有属性“用户名”
- java - 如何将 ExecuteService 与包含 AutoCloseable 资源的自定义线程一起使用