媒体播放器 mp3 不工作 wpf [英] mediaplayer mp3 not working wpf

查看:39
本文介绍了媒体播放器 mp3 不工作 wpf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 WPF 应用程序中遇到 MediaPlayer 类的问题.
我的项目如下所示:

I have an issue with MediaPlayer class in WPF application.
My project looks like this:

问题是:当我的 AboutDialog 被初始化并出现时,它不播放 AboutDialogSound.mp3.我认为问题是 Uri 字符串格式,我尝试更改它但我仍然没有工作.

The issue is: When my AboutDialog is initialized and appears, it doesn't play the AboutDialogSound.mp3. I think the problem is the Uri string format, I tried changing it but I still didn't work.

对不起,我不擅长英语.请帮我解决这个问题.提前致谢.

I'm sorry I'm not good at English. Please help me with this issue. Thanks in advance.

推荐答案

至少,您的代码有两个问题,关于您如何尝试使用 MediaPlayer 播放 mp3 文件:

At least, there are two problems in your code, regarding how you attempted to play mp3 file using MediaPlayer :

  1. 您已经怀疑的主要问题是文件路径错误.相对路径是指相对于可执行文件.在开发阶段,它位于 bin\debug 文件夹中.所以mp3文件的路径应该是"../../AboutDialogSound.mp3".
  2. 另一个问题是将 MediaPlayer 对象声明为局部变量.通过这样做,对象将在声明变量的方法(在本例中为 AboutDialog 构造函数)完成后不久被垃圾收集.因此,如果您设法解决了第一个问题,您会听到音频文件播放了一会儿,然后突然停止了,因为 MediaPlayer 正在播放它.将其声明为全局变量而不是本地变量.
  1. The main problem as you already suspected, is the wrong path to the file. Relative path means relative to the executable file. In development phase, it is inside bin\debug folder. So the path to the mp3 file should be "../../AboutDialogSound.mp3".
  2. Another problem is declaring MediaPlayer object as local variable. By doing this, the object will be garbage-collected soon after the method where variable declared (AboutDialog constructor in this case) finished. So if you managed to fix the first problem, you will hear audio file played for a moment, then suddenly stopped because the MediaPlayer playing it GC-ed. Declare it as global variable instead of local.

提示:要检查MediaPlayer是否失败(如路径错误导致找不到文件),请尝试订阅MediaFailed事件.因为MediaPlayer 不抛出异常,而是触发MediaFailed 事件.

Tips : To check for failure in MediaPlayer (such as file not found because of the wrong path), try to subscribe to the MediaFailed event. Because MediaPlayer doesn't throw exception, it trigger MediaFailed event instead.

public partial class AboutDialog
{
    private MediaPlayer player;

    public AboutDialog()
    {
        player = new MediaPlayer();
        player.MediaFailed += (o, args) =>
                                  {
                                      MessageBox.Show("Media Failed!!");
                                  };
        player.Open(new Uri("../../AboutDialogSound.mp3", UriKind.RelativeOrAbsolute));
        player.Play();
    }
    .....
}

参考:http://www.wpf-tutorial.com/audio-视频/播放-音频/

这篇关于媒体播放器 mp3 不工作 wpf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆