How to play WAV audio file from Resources? - c#

How can I play a WAV audio file in from my project's Resources? My project is a Windows Forms application in C#.

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.
Open "Solution Explorer" from menu toolbar ("VIEW") or simply press Ctrl+Alt+L.
Click on drop-down list of "Properties".
Then select "Resource.resx" and press enter.
Now select "Audio" from the combobox list.
Then click on "Add Resource", choose audio files (.wav) and click "Open".
Select audio file(s) and change "Persistence" properties to "Embedded in .resx".
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. :)

Stream str = Properties.Resources.mySoundFile;
RecordPlayer rp = new RecordPlayer();
rp.Open(new WaveReader(str));
rp.Play();
From How to play WAV audio file from resources in C#.

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.

Theses two lines can do it:
SoundPlayer sound = new SoundPlayer(Properties.Resources.solo);
sound.Play();

There are two ways to do so as far as I know, list below:
Use file path
First put the file in the root folder of the project, then no matter you run the program under Debug or Release mode, the file can both be accessed for sure. Then use the class SoundPlayer to paly it.
But in this way, if you want to release the project to users, you need to copy the sound files with its folder hierarchies except hierarchies the folder "Release" under the "bin" directory.
var basePath = System.AppDomain.CurrentDomain.BaseDirectory;
SoundPlayer player = new SoundPlayer();
player.SoundLocation = Path.Combine(basePath, #"./../../Reminder.wav");
player.Load();
player.Play();
Use resource
Follow below animate, add "Exsiting file" to the project.
SoundPlayer player = new SoundPlayer(Properties.Resources.Reminder);
player.Play();
The strength of this way is:
Only the folder "Release" under the "bin" directory need to be copy when run the program.

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.
using System.Media; //write this at the top of the code
SoundPlayer my_wave_file = new SoundPlayer("F:/SOund wave file/airplanefly.wav");
my_wave_file.PlaySync(); // PlaySync means that once sound start then no other activity if form will occur untill sound goes to finish
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(); with my_wave_file.PlayAsync();.

Related

Playing WPF music as a resource [duplicate]

I am trying to play a sound file in my WPF application. Currently I have the following call:
private void PlaySound(string uriPath)
{
Uri uri = new Uri(#"pack://application:,,,/Media/movepoint.wav");
var player = new MediaPlayer();
player.Open(uri);
player.Play();
}
Now if I specify Media/movepoint.wav as build action Content and load it as a relative or absolute file path it works fine, so I suspect this has something to do with the Pack URI, but I cannot for the life of me figure out what.
The objective is to store the file as a resource so that its not available in the output directory. I can provide either the WAV copy or the MP3 copy.
I tried this with an image file, which works the same as a sound file as far as the uri is concerned because it's just another resource. I used the code below which essentially matches what you have.
new Uri(#"pack://application:,,,/Resources/logo.png")
Make sure that your 'Media' folder is not nested in any other folder. If it is, you need to include that folder as well.
Using .NET Framework 4.0, VS2012.
This link gives a pretty good description of the whole "pack" scheme of things.
EDIT
More research on this topic seems to indicate that what you want to do might not be possible with audio or video files. The excerpt below is taken from the remarks section of this MSDN page.
Although you can declare an instance of this class in Extensible
Application Markup Language (XAML), you cannot load and play its media
without using code. To play media in XAML only, use a MediaElement.
Also, if you declare an instance in XAML, the only practical use is to
fill property element syntax for the Player property.
When distributing media with your application, you cannot use a media
file as a project resource. In your project file, you must instead set
the media type to Content and set CopyToOutputDirectory to
PreserveNewest or Always.
MediaPlayer can be used in two different modes, depending on what is
driving the player: independent mode or clock mode. In independent
mode, the MediaPlayer is analogous to an image and the media opened
through the Open method drives playback. In Clock mode, the
MediaPlayer can be thought of as a target for an animation, and thus
it will have corresponding Timeline and Clock entries in the Timing
tree which controls playback. For more information on media modes, see
the Multimedia Overview.
MediaPlayer is different from a MediaElement in that it is not a
control that can be added directly to the user interface (UI) of an
application. To display media loaded using MediaPlayer, a VideoDrawing
or DrawingContext must be used.
The following seems to work in .NET Framework 4.5:
var sri = Application.GetResourceStream(new Uri("pack://application:,,,/MyAssemblyName;component/Resources/CameraShutter.wav"));
if ((sri != null))
{
using (s == sri.Stream)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(s);
player.Load();
player.Play();
}
}
CameraShutter.wav is embedded as Resource in my project (and resides inside Resources subfolder, as indicated in the pack URI).
You can also load a Stream into the SoundPlayer if the .wav file is an Embedded Resource. Note that in this example the resources are in a folder called Resources that is in the root of the project, that is why it is written {0}.Resources.{1}.
//the wav filename
string file = "emergency_alarm_002.wav";
//get the current assembly
var assembly = System.Reflection.Assembly.GetExecutingAssembly();
//load the embedded resource as a stream
var stream = assembly.GetManifestResourceStream(string.Format("{0}.Resources.{1}", assembly.GetName().Name, file));
//load the stream into the player
var player = new System.Media.SoundPlayer(stream);
//play the sound
player.Play();
This also seems to work and is maybe simpler to remember than that long line of pack or assembly stuff..
I opened the Resources.resx and dragged a sound file in there called aa_pickup.wav Then set the properties of it to Copy to Output Dir = Copy Always.
System.IO.Stream str = Properties.Resources.aa_pickup;
System.Media.SoundPlayer snd = new System.Media.SoundPlayer(str);
snd.Play();
Now.. if I could only work out how to change the volume.

How to use a Embedded file from Assembly for SoundPlayer contexts inside of a C# application

Hello Stack Overflow community,
I have been working on making a custom installer/launcher for the game I am making, it is currently in working in a non-portable context, however if I want to put it inside of a game for distribution, it must work inside of a portable context (i.e. it should not access the drive for any of it's own needs, only the other software's needs)/
At the current moment it loads a song from the drive to play, and as well loads the prerequisites for the game if the launcher has never been opened before or did not finish successfully. The files are all set to "EmbeddedResource" inside of SharpDevelop, and they are part of the final compiled script.
However, in the code's current context, the script still has to access the drive to do all of those functions, even when they are embedded into the final program.
The current code I have so far is below, "programpath" refers to the directory of which the file is being executed from, "MainText" is the main output window, which is better seen in this Stack Overflow question, and label1 is a debug line, that is only used to show the path of the current running command (will be removed when all the things are embedded).
public MainForm()
{
//Open Window
InitializeComponent();
CenterToScreen();
//Start song
System.Media.SoundPlayer player = new System.Media.SoundPlayer(programpath+"\\Resonance.wav");
player.PlayLooping();
this.Shown+=(s,e)=>{
if(File.Exists(programpath+"\\FirstLaunch.lic")&&File.ReadAllText(programpath+"\\FirstLaunch.lic").IndexOf("Installation Successful")>=0){
BackColor=System.Drawing.Color.OrangeRed;
MainText.BackColor=System.Drawing.Color.OrangeRed;
MainText.ForeColor=System.Drawing.Color.Aquamarine;
MainText.Text="Starting game..";
Process game = new Process();
//placeholder executable, will be finished game executable
game.StartInfo.FileName="D:\\UT2004\\System\\UT2004.exe";
game.StartInfo.ErrorDialog=true;
game.Start();
//stop playing music,
player.Stop();
//when game stops, close the launcher
game.WaitForExit();
Application.Exit();
}else{
//Start prerequisite installation
newLaunch();
}
};
}
//if the launcher has not been open before OR the last installation was not successful
void newLaunch(){
//Creates and makes a stream to the file
StreamWriter writer = new StreamWriter(programpath+"\\FirstLaunch.lic");
//Changing color scheme
BackColor=System.Drawing.Color.Chartreuse;
MainText.BackColor=System.Drawing.Color.Chartreuse;
MainText.ForeColor=System.Drawing.Color.Black;
MainText.Text="Configuring Prerequisites....\nInstalling DirectX";
//write to file about stage
writer.Write("Installing DirectX");
//start DirectX installer
Process prerequisite = new Process();
prerequisite.StartInfo.FileName=programpath+"\\dxwebsetup.exe";
prerequisite.StartInfo.ErrorDialog=true;
prerequisite.Start();
//debug line
label1.Text=programpath+"\\dxwebsetup.exe";
//wait for installer to finish and close
prerequisite.WaitForExit();
//remove refernce to DirectX installer
prerequisite.Close();
//write to file about stage
writer.WriteLine("...true");
//Changing color scheme
BackColor=System.Drawing.Color.DarkMagenta;
MainText.BackColor=System.Drawing.Color.DarkMagenta;
MainText.ForeColor=System.Drawing.Color.Yellow;
MainText.Text="Configuring Prerequisites....\nInstalling Microsoft VC++2015 Update RC3";
//write to file about stage
writer.Write("Installing VCRedist");
//start VC Redistributable installer
prerequisite.StartInfo.FileName=programpath+"\\vc_redist.x86.exe";
prerequisite.StartInfo.ErrorDialog=true;
prerequisite.Start();
//debug line
label1.Text=programpath+"\\vc_redist.x86.exe";
//wait for installer to finish and close
prerequisite.WaitForExit();
//remove reference to VC Redistributable installer
prerequisite.Close();
//write to file about stage
writer.WriteLine("...true");
writer.WriteLine("Installation Successful");
writer.Close();
//re-open launcher from open context
label1.Text=programpath+"\\ColorLoop.exe";
Process.Start(programpath+"\\ColorLoop.exe");
Application.Exit();
}
}
}
How do I get the program to play the music, and load the pre-requisites from itself and not from separate drive files inside the code. It is all already embedded, just not being used.
I finaly figured it out, so I am answering my own question in the hopes that people who are struggling in the future can figure it out.
Using the link provided by #Jimi for Accessing Resources in SharpDevelop, and scrolling down to the "Embedding Files directly" section, shows the context at which to access Embedded Resource. The thing to note here is that the return type of GetManifestStream(string) is a System.IO.Stream object.
This is important as we need SoundPlayer to accept a System.IO.Stream object some how. This can be done two ways, by using an overloaded constructor or Property of the SoundPlayer class. As defined by the MSDN page for the SoundPlayer Class.
However, when I tested this, I could not get the sound to play. Furthering my research, I found that Assembly.GetExecutingAssembly() has a accessible method named "GetManifestResourceNames()" that returns a string array of all the resources and their corrective names to access them. I was able to see the return by creating a Windows Form Label called "ExecutingAssem", and using the instructions from DotNetPerls to create a static method named "ConvertStringArrayToStringJoin()", but changing its seperator from "." to "|" to better read the assets.
With that in place the final program shows the list of embedded resources with the line:
ExecutingAssem.Text=ConvertStringArrayToStringJoin(Assembly.GetExecutingAssembly().GetManifestResourceNames());
And the final program appearing as:
Program showing all the resources in the corner
The interesting thing here is that the song resource (Resonance) is not actually a part of the Namespace, or MainForm...but rather its own name as the resource title.
With that missing information found, I needed to change the program from reading the drive to reading the manifest stream. Using the overloaded constructor that utilizes a System.IO.Stream object as a parameter instead of a string to a file location, I changed where the player object is initiated to use that constructor.
SoundPlayer player =new SoundPlayer(Assembly.GetExecutingAssembly().GetManifestResourceStream("Resonance"));
Finally the final application played the song with the ability to move the .exe file elsewhere and still be able to play the same song without "Resonance.wav" needing to be in the same directory.
private void button1_Click(object sender, EventArgs e)
{
SoundPlayer player = new SoundPlayer();
//Add TestSound.wav file to the built-in resource file Project>Properties>Resources.resx
player.Stream = Properties.Resources.TestSound;
//Add TestSound.wav file to a new resource file Resource1.resx
//player.Stream = Resource1.TestSound;
player.Play();
}

c# opening an embedded file (.doc, .pdf, .exe etc.)

I am new to C# and I have normally built windows forms using VB and was able to use one code to open any embedded file I added to my "Resources". As far as C# I have looked online for hours and have yet to find anything that worked. Please assist in any way that you can.
I have a Windows Form that will have a single button that will be assigned to open a particular file I have added to the "Resources" folder. Usually I would use the following code to have a Button_Click to load an exe, doc or pdfile. I am looking for something similar for C#.
VB Code:
IO.File.WriteAllBytes(My.Computer.FileSystem.SpecialDirectories.Temp & "\IEResetConfigure.exe", My.Resources.IEResetConfigure)
Process.Start(My.Computer.FileSystem.SpecialDirectories.Temp & "\IEResetConfigure.exe")
Simply write your resource file to temporary directory and run the file
using System;
using System.IO;
using System.Diagnostics;
// ...
byte[] resourceFile = Properties.Resources.Newspaper_PC_13_12_2013;
string destination = Path.Combine(Path.GetTempPath(), "Newspaper_PC_13_12_2013.pdf");
System.IO.File.WriteAllBytes(destination, resourceFile);
Process.Start(destination);
Example of my comment
using System;
using System.IO;
using System.Diagnostics;
using System.Threading.Tasks;
// ...
static void Main(string[] args)
{
byte[] resourceFile = Properties.Resources.Newspaper_PC_13_12_2013;
string destination = Path.Combine(Path.GetTempPath(), "Newspaper_PC_13_12_2013.pdf");
File.WriteAllBytes(destination, resourceFile);
Process.Start(destination);
AutoDelete(2000, destination);
Console.Write("Press any key to quit . . . ");
Console.ReadKey(true);
}
static async void AutoDelete(int milliseconds, string destination)
{
while (File.Exists(destination))
{
await Task.Delay(milliseconds);
try
{
File.Delete(destination);
}
catch
{
continue;
}
}
}
For anyone still looking, Here is a way of opening an "embedded" file. I'd love for someone to correct me below on a better way.
The first part is to make sure your file is added to your project in the bin\debug folder.
I then used this code to call it
private void button1_Click(object sender, EventArgs e)
{
//Place file in .\bin\Debug folder of project
string filename = "YourFileName.pdf";
System.Diagnostics.Process.Start(filename);
For full Disclosure this whole part has been stolen from
(Opening a .pdf file in windows form through a button click)
I did however run into an issue where after the first build that didn't work for me. So when I created the setup project I added the "Project Output" and then added in my pdf via "add file" to the application folder.
That has continued to work flawlessly for me since.
This is my first post on Stack Overflow, so please let me know if I misunderstood any rules or could improve. Thank you and I hope this helped!

Open video file in C#

I am new to C# and this might sound stupid, I did some research and I think I am confused.
I want my c# program to open a video file (c:\abc.mov), I have set the .mov files to open automatically with quick time player and I want the program to open the file with quick time player just like double clicking on that file.
When I use this code it does not do anything!
File.Open(#"c:\abc.mov", FileMode.Open);
Please help me?
You should use Process.Start instead. Here's the MSDN page on that.
You can specify which program you want to start with whetever arguments you need, like in this example.
Edit: Added another example. Thanks #DJBurb
Process.Start(#"c:\\abc.mov");
This code should open the .mov file with the default movie player associated with the .mov extension.
This will open your video file with the dafault video player
System.Diagnostics.Process.Start(filepath);
i believe that open() will open your file for editing for this current program, not actually opening the file with your system's default player
File.Open returns FileStream so you can read that file, instead you most definitely want to use Process.Start(#"c:\abc.mov");
private void buttonOpen_Click(object sender, EventArgs e)
{
if (ofd.ShowDialog()==DialogResult.OK)
{
Process.Start(ofd.FileName);
}
}

Playing wav file, concatenating string to call file

I am (after some strangeness with my resources file) able to play a .wav file in my project:
SoundPlayer player = new SoundPlayer();
player.Stream = Sounds.L1;
Player.Play();
This works fine but what I want to do is be able to concatenate a string together and then call the file. The .wav filename would be of the form "L" + int, with int being anywhere between 1 - 99 i.e. L1, L2...L99. All the different sound files are in a resx file title Sounds.
How would I be able to call them?
I am trying to use the ResXResourceSet resxSet = new ResXResourceSet("btc.Sounds") ResXResourceSet to load the resources file and then use the .getobject() as suggested. However, how do you specify the location of the embedded resource file? If I use a path as above I get an error as it is looking in my bin/debug folder, which is where the .exe is placed. If I explicityly specify the path I get an access error and one thing I am really curious about is the fact that the 'Sounds.resx' file is an embedded resource so it should 'know' where it is and shouldn't need any path... I have tried pretty much every permutation including using Assembly.GetExecutingAssembly().GetManifestResourceStream("btc_I_Cap.Sounds"), #"....\Sounds" #"....\Resources", #"btc.Sounds" "Sounds.resx" and so on and so far nothing. Can someone please put me out of my misery so that I can go 'oh yeah, that was obvious why didn't I think of that!'
Happy halloween.
Thanks.
Use a ResXResrouceSet to call the sound file Something like this:
using (ResXResourceSet resxSet = new ResXResourceSet(resxFile))
{
for (int i = 1; i <= 99; i ++)
{
SoundPlayer simpleSound = (SoundPlayer)resxSet.GetObject("L" + i.ToString());
simpleSound.Play();
}
}

Categories

Resources