C# - Play audio in program, on any computer? [clos

2019-08-31 03:32发布

I want to have a checkbox that can enable/disable background music in my winforms application. I found out how to load a specific file from a directory with openfiledialog and such but that was bad, so I did this (worked on my pc):

if (checkBox7.Checked == true)
        {
            System.Media.SoundPlayer player = new System.Media.SoundPlayer();
            player.SoundLocation = "PATH";
            player.Load();
            player.Play();
        }

But how in the world do I get it to work on other computers? I know I could put an mp3 file inside the same folder with the program, and send that folder to another person. But I've seen programs where the mp3/wav (or whatever) is built-in inside the application and there's only an exe file.

An example are those "keygenerators" for different applications like Sony Vegas. How did he include the audio file inside the program?

Could anyone help? I tried adding a wav file to the resources and then use that as path, but it's not possible for some reason...?

path would be for example: MyProgram.Properties.Resources.Song but I could not add .wav or .mp3 at the end, so it can't load the file.

Any help is appreciated! I want the sound to be in background and hidden, no media player showing and so on. And no "browse file" button. I just want it to load my song automatically which should be included inside the program in some way.

标签: c# .net audio mp3 wav
1条回答
狗以群分
2楼-- · 2019-08-31 03:54

Embed it as resource (just add that file to your project as resource and it'll be embedded inside assembly).

You'll be able to write (I assume your resource file is named Resources.resx and your imported resource for audio file is NameOfYourResource) this using SoundPlayer that accepts a stream:

using (var stream = Resources.ResourceManager.GetStream("NameOfYourResource"))
using (var player = new SoundPlayer(stream))
{
    player.PlaySync();
}

Of course this is not the only method! You may (still using resources) write it to a temporary file (then you'll play that).

You may also append files to play at the end of you assembly (yes, after it has been compiled):

  • Compile your assembly.
  • As post-build step append your audio file to your executable (raw data after raw data).
  • Add an extra Int32 chunk to your assembly with its size without audio file.

To play it:

  • Read last 4 bytes of your own executable.
  • Open a stream to it and use that size as offset.
  • Play from there.

This is more tricky but it has advantage that audio file won't be visible as resource (in case you care about it or you want to use this method for something else).

查看更多
登录 后发表回答