How can I play a WAV audio file in from my project's Resources? My project is a Windows Forms application in C#.
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Can we recover audio from MFCC coefficients?
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
From How to play WAV audio file from resources in C#.
Because
mySoundFile
is aStream
, you can take advantage ofSoundPlayer
's overloaded constructor, which accepts aStream
object:SoundPlayer Class Documentation (MSDN)
When you have to add sounds into your project, you will do so by playing
.wav
file(s). Then you have to add the.wav
file(s) like this.Remember that you have to write the path of the file with forward slashes (
/
) format, don't use back slashes (\
) when giving a path to the file, else you will get an error.Also note, if you want other things to happen while the sound is playing, you can change
my_wave_file.PlaySync();
withmy_wave_file.PlayAsync();
.a) OK, first add audio file (.wav) into project resource.
b) Now, just write this code to play the audio.
In this code I'm playing audio on form load event.
That's it.
All done, now run the project (press f5) and enjoy your sound.
All the best. :)
You need to be cautious about the garbage collector freeing up memory used by your sound while the sound is still playing. While it rarely happens, when it does, you will just be playing some random memory. There is a solution to this, complete with source code for achieving what you want here: http://msdn.microsoft.com/en-us/library/dd743680(VS.85).aspx
Scroll to the very bottom, in the "Community Content" section.