Search code examples
c#wpfsoundplayer

Issue with SoundPlayer


Situation

this is probably a really simple question with a really simple answer, but I can't find the answer anywhere, so I'm going to ask here, I've been working around this because it isn't a huge issue for me, but it will be when I submit my work.

Problem

I have a soundplayer, it works fine on my PC and does exactly what I want it to do on this PC.

SoundPlayer player = new SoundPlayer(@"C:\Users\Font\Desktop\GRADED_UNIT_SOLUTION_PLANNING_UPDATED\HillRacingGraded\HillRacingGraded\Resources\Audio\" + track + ".wav");

The problem is the path.

because of THIS path my program won't work on ANY other System apart from the one it's working on right now. It crashes soon after startup.

And.. as you can probably see from the path, it's going to eventually be graded, so my lecturer will need to use this program without having to switch around a directory.

How can I get the Soundplayer path to start at "HillRacingGraded\ ...\ ..."?

Rather than it starting at the C: drive.


Solution

  • If you're using System.Media.SoundPlayer, it supports reading of sound files from streams and I've seen it successfully used in the past from the UnmanagedResourceStream you get from an embedded resource. So one option would be to embed your sound file as a resource in your application and play it from there.

    If embedding the file isn't an option, you can get paths relative to your executable folder using code similar to that shown below. Then you just have to provide your executable and the resource files in a subdirectory (but be careful with GetExecutingAssembly() if there's any chance your code is in a DLL and can be hosted by an arbitrary executable).

    var assembly = Assembly.GetExecutingAssembly();
    var folder = Path.GetDirectoryName(assembly.Location);
    var soundFile = Path.Combine(folder, "MySoundFile.wav");
    

    The special folder path helpers can also reduce the hard-coding but work best when your application will be installed via an installer and you can put files in the appropriate places automatically (which isn't likely to be the case for a school project).