How can I play a WAV audio file in from my project's Resources? My project is a Windows Forms application in C#.
Since WAV is quite a popular format, almost all devices today support it using built-in media players. On Windows, the Windows Media Player is capable of playing WAV files. On MacOS, iTunes or QuickTime can play WAV files. On Linux, your basic ALSA system can play these files.
WAV files are widely used, and because of this, many programs can open them on different platforms—Windows Media Player, Winamp, iTunes, VLC, and QuickTime, to name a few. Windows and macOS users can play WAV files right out of the box without having to install any third-party software.
Poweramp Music Player is a powerful WAV file player for Android.
Because mySoundFile
is a Stream
, you can take advantage of SoundPlayer
's overloaded constructor, which accepts a Stream
object:
System.IO.Stream str = Properties.Resources.mySoundFile; System.Media.SoundPlayer snd = new System.Media.SoundPlayer(str); snd.Play();
SoundPlayer Class Documentation (MSDN)
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.
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Media; // at first you've to import this package to access SoundPlayer namespace WindowsFormsApplication1 { public partial class login : Form { public login() { InitializeComponent(); } private void login_Load(object sender, EventArgs e) { playaudio(); // calling the function } private void playaudio() // defining the function { SoundPlayer audio = new SoundPlayer(WindowsFormsApplication1.Properties.Resources.Connect); // here WindowsFormsApplication1 is the namespace and Connect is the audio file name audio.Play(); } } }
That's it.
All done, now run the project (press f5) and enjoy your sound.
All the best. :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With