Use DLL resources for WPF MediaPlayer

2019-01-27 05:49发布

问题:

In my project I have a DLL for some WPF/XAML controls that need to play some audio files. Now, with SoundPlayer I can make these audio files "Embedded Resources" of the DLL (that also contains the WPF controls). However, SoundPlayer has some severe limitation so I switched to MediaPlayer.

Unfortunately, the MediaPlayer help page states that MediaPlayer can't work with resources. (I tried using Pack URIs anyway but this didn't work - at least none of the combinations I've tried.) So, for now, I'm writing the DLL resources (audio files) to temporary files and then use them with MediaPlayer, but that's IMHO not a "good" solution.

So, I was wondering if there is a "correct" way in WPF with MediaPlayer to place audio files in a DLL project.

The help page states that the (audio) files should be marked as "Content" and use "Copy to Output Directory" but obviously this only works for file that are part of the EXE project. It doesn't work for a DLL project.

回答1:

As you discovered MediaPlayer does not support loading media from resources.

The simplest option is to distribute the sound files with your application and place them in the application folder - Content/"Copy to Output Directory" does just that.

If you hit a limitaiton of Visual Studio build system you can just copy the files yourself (drag/drop them into the bin/Debug or bin/Release folser of the exe project) or write a batch file that will copy them and use it as a post-build action.

Obviously, when you ship the applicaiton to an end user you have to make sure the files are copied correctly.

If you are writing a DLL to be used by other develpers and you don't want manual file copying to be part of the developer's installation process you can always use a registry key that points to the files location (set by the DLL's installer) - and fall back to the EXE folder if the registry key is missing (so the EXE developer still has to bundle the files with the EXE but doesn't need to mess with anything during development).

And, of course, if you must have the DLL as a one file standalone package you are left only with the "extract to temp folder" option you already use.



回答2:

For those interested in the solution, I wrote an article with a workaround solution. You can find it here:

http://www.codeproject.com/KB/audio-video/wpfaudioplayer.aspx