c# - 如何播放 WPF 声音文件资源

标签 c# .net wpf media-player

我正在尝试在我的 WPF 应用程序中播放声音文件。目前我有以下电话:

private void PlaySound(string uriPath)
{
    Uri uri = new Uri(@"pack://application:,,,/Media/movepoint.wav");
    var player = new MediaPlayer();
    player.Open(uri);
    player.Play();
}

现在,如果我将 Media/movepoint.wav 指定为构建操作 Content 并将其作为相对或绝对文件路径加载,它工作正常,所以我怀疑这有问题与 Pack URI 相关,但我终究无法弄清楚是什么。

目标是将文件存储为资源,使其在输出目录中不可用。我可以提供 WAV 副本或 MP3 副本。

最佳答案

我用一个图像文件尝试了这个,就 uri 而言,它与声音文件的工作方式相同,因为它只是另一种资源。我使用了下面的代码,它基本上与您所拥有的相匹配。

new Uri(@"pack://application:,,,/Resources/logo.png")

确保您的“媒体”文件夹未嵌套在任何其他文件夹中。如果是,您还需要包含该文件夹。

使用 .NET Framework 4.0、VS2012。

This link很好地描述了事物的整个“打包”方案。

编辑

关于此主题的更多研究似乎表明您想要执行的操作可能无法通过音频或视频文件实现。以下摘录自this MSDN page的备注部分.

Although you can declare an instance of this class in Extensible Application Markup Language (XAML), you cannot load and play its media without using code. To play media in XAML only, use a MediaElement. Also, if you declare an instance in XAML, the only practical use is to fill property element syntax for the Player property.

When distributing media with your application, you cannot use a media file as a project resource. In your project file, you must instead set the media type to Content and set CopyToOutputDirectory to PreserveNewest or Always.

MediaPlayer can be used in two different modes, depending on what is driving the player: independent mode or clock mode. In independent mode, the MediaPlayer is analogous to an image and the media opened through the Open method drives playback. In Clock mode, the MediaPlayer can be thought of as a target for an animation, and thus it will have corresponding Timeline and Clock entries in the Timing tree which controls playback. For more information on media modes, see the Multimedia Overview.

MediaPlayer is different from a MediaElement in that it is not a control that can be added directly to the user interface (UI) of an application. To display media loaded using MediaPlayer, a VideoDrawing or DrawingContext must be used.

关于c# - 如何播放 WPF 声音文件资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15145209/

相关文章:

c# - 尽管有错误处理,Windows 8.1 XAML 应用程序还是崩溃

c# - C# 中双向关联的值相等

c# - 如何计算 WPF 绑定(bind)中的值

wpf - 如何在 WPF 中制作圆角形式?

c# - 如何从我的方法外部访问 c sharp 中的对象?

c# - XML 正则表达式替换

c# - WPF 中的 OpenGL 控件因 OOM 异常而崩溃

c# - AutoMapper - 条件映射

.net - 应用程序未清除表单关闭上的对话框内容

.net - Quartz Scheduler - 触发器不引用给定的作业