I'm trying to play a sound file in my application through the MediaPlayer class from Resources, but I get an error
Ошибка
private void button1_Click(Object sender, EventArgs e) { var p1 = new System.Windows.Media.MediaPlayer(); p1.Open(new Uri(@"pack://application:,,,/Resources/_1.wav")); p1.Play(); }
What is wrong with my path?

    1 answer 1

    The problem is that MediaPlayer does not support Pack URI . Therefore, it is necessary to keep the media files in the unpacked form (at least next to the exe file), and open them using the relative URI.

    For the convenience of managing media files and deploying the application, files can be added to the project and set their "Copy to Output Directory" property in "Copy Always" or "Copy if Newer". For more details, see the accepted answer to this question:

    If for some reason the media files need to be packaged into an exe file, then you need to extract and save them from it into temporary files before playing.

    To extract a file from application resources, you can use the Assembly.GetManifestResourceStream method. The method parameter is passed the path, which starts with the Default Namespace , and then the path to the file in the project itself. A dot is used instead of a slash.

     Assembly executingAssembly = Assembly.GetExecutingAssembly(); Stream resourceStream = executingAssembly.GetManifestResourceStream("ApplicationDefaultNamespace.Resources._1.wav"); Stream fileStream = File.OpenWrite("_1.wav"); resourceStream.CopyTo(fileStream); fileStream.Flush(); fileStream.Close(); Uri relativeUri = new Uri("_1.wav"); p1.Open(relativeUri); 

    The following materials were used to write the answer:

    Media element and uri resource

    WPF | Resource Usage | Packaged URIs

    Save and load MemoryStream to / from a file