我需要使用仅MediaPlayer 类在Windows应用中运行.wav文件,并且需要在运行时加载MediaPlayer类的程序集require。我需要使用PresentationFramework.dll,WindowsBase.dll和PresentationCore.dll。 MediaPlayer的对象创建成功,但在尝试调用MediaPlayer构造函数时,它失败了。以下是代码:
Assembly assembly = Assembly.LoadFrom("PresentationCore.dll");
Type type = assembly.GetType("System.Windows.Media.MediaPlayer");
object instanceOfMyType = Activator.CreateInstance(type);
type.InvokeMember("MediaPlayer", BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, instanceOfMyType,null);
type.InvokeMember("Open", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, instanceOfMyType, new object[] { new Uri("C:\\MyMusic\\Song1.wav") });
type.InvokeMember("Play", BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, instanceOfMyType, null);
但是不起作用..它在这一行给出错误
type.InvokeMember("MediaPlayer", BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.SetProperty, null, instanceOfMyType,null);
我是否需要加载所有程序集或仅需要PresentationCOre.dll。不是用户如何运行这个。
使用的参考 - > http://edu-kinect.com/blog/2014/07/10/reflection-examples-c/
谢谢,
答案 0 :(得分:1)
考虑到这个序列正常工作(你需要在WinXP上使用Windows Media Player> 10或在以后的操作系统中启用媒体功能),不要像@HansPassant所提到的那样提出一个坏主意:
var mediaPlayer = new System.Windows.Media.MediaPlayer();
mediaPlayer.MediaFailed += (o, ev) =>
Debug.WriteLine("Media Failed: {0}", ev.ErrorException.Message);
mediaPlayer.MediaOpened += (sender, e) => Debug.WriteLine("Media Opened");
//string mediaFilePath =
Uri uri = new Uri(mediaFilePath, UriKind.RelativeOrAbsolute);
mediaPlayer.Open(uri);
mediaPlayer.Play();
然后反映上面这样的序列也应该有效:
Type type = Type.GetType("System.Windows.Media.MediaPlayer, PresentationCore, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");
object instanceMediaPlayer = Activator.CreateInstance(type);
// string mp3FilePath = ...;
var uri = new Uri(mp3FilePath, UriKind.RelativeOrAbsolute);
BindingFlags bfMethodCall = BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public;
type.InvokeMember("Open", bfMethodCall, null, instanceMediaPlayer, new object[] { uri });
type.InvokeMember("Play", bfMethodCall, null, instanceMediaPlayer, null);
此外,我发现您使用的是wav文件作为源代码。如果你只需要播放未压缩的wav文件(没有其他媒体格式或压缩的wavs)并且你不想控制音量或其他播放方面,那么更轻量级的SoundPlayer
就足够了,而不需要加载任何额外的引用
var soundPlayer = new System.Media.SoundPlayer();
soundPlayer.SoundLocation = @"pathTo.wav";
soundPlayer.Load();
soundPlayer.Play();