How to play a sound in C#, .NET - c#

I have a Windows application written in C#/.NET.
How can I play a specific sound when a button is clicked?

You could use:
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"c:\mywavfile.wav");
player.Play();

You can use SystemSound, for example, System.Media.SystemSounds.Asterisk.Play();.

For Windows Forms one way is to use the SoundPlayer
private void Button_Click(object sender, EventArgs e)
{
using (var soundPlayer = new SoundPlayer(#"c:\Windows\Media\chimes.wav")) {
soundPlayer.Play(); // can also use soundPlayer.PlaySync()
}
}
MSDN page
This will also work with WPF, but you have other options like using MediaPlayer MSDN page

Additional Information.
This is a bit high-level answer for applications which want to seamlessly fit into the Windows environment. Technical details of playing particular sound were provided in other answers. Besides that, always note these two points:
Use five standard system sounds in typical scenarios, i.e.
Asterisk - play when you want to highlight current event
Question - play with questions (system message box window plays this one)
Exclamation - play with excalamation icon (system message box window plays this one)
Beep (default system sound)
Critical stop ("Hand") - play with error (system message box window plays this one)
 
Methods of class System.Media.SystemSounds will play them for you.
 
Implement any other sounds as customizable by your users in Sound control panel
This way users can easily change or remove sounds from your application and you do not need to write any user interface for this – it is already there
Each user profile can override these sounds in own way
How-to:
Create sound profile of your application in the Windows Registry (Hint: no need of programming, just add the keys into installer of your application.)
In your application, read sound file path or DLL resource from your registry keys and play it. (How to play sounds you can see in other answers.)

Code bellow allows to play mp3-files and in-memory wave-files too
player.FileName = "123.mp3";
player.Play();
from http://alvas.net/alvas.audio,samples.aspx#sample6 or
Player pl = new Player();
byte[] arr = File.ReadAllBytes(#"in.wav");
pl.Play(arr);
from http://alvas.net/alvas.audio,samples.aspx#sample7

To play an Audio file in the Windows form using C# let's check simple example as follows :
1.Go Visual Studio(VS-2008/2010/2012) --> File Menu --> click New Project.
2.In the New Project --> click Windows Forms Application --> Give Name and then click OK.
A new "Windows Forms" project will opens.
3.Drag-and-Drop a Button control from the Toolbox to the Windows Form.
4.Double-click the button to create automatically the default Click event handler, and add the following code.
This code displays the File Open dialog box and passes the results to a method named "playSound" that you will create in the next step.
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Audio Files (.wav)|*.wav";
if(dialog.ShowDialog() == DialogResult.OK)
{
string path = dialog.FileName;
playSound(path);
}
5.Add the following method code under the button1_Click event hander.
private void playSound(string path)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer();
player.SoundLocation = path;
player.Load();
player.Play();
}
6.Now let's run the application just by Pressing the F5 to run the code.
7.Click the button and select an audio file. After the file loads, the sound will play.
I hope this is useful example to beginners...

I think you must firstly add a .wav file to Resources. For example you have sound file named Sound.wav. After you added the Sound.wav file to Resources, you can use this code:
System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.Sound);
player.Play();
This is another way to play sound.

Related

Kinect Hovering event handler

I am creating a WPF application using Kinect SDK 1.8
I want to press a button with hand.
private void playTeeth1Sound(object sender,RoutedEventArgs e)
{
System.Media.SoundPlayer teeth1_Sound = new System.Media.SoundPlayer(#"../../soundForKinect/1.wav");
teeth1_Sound.Play();
}
I don't see any Kinect specific code in your question, and I'm not sure what the questions is, but one thing to consider in the code snippet in your question is:
Every time this method is called (presumably when the button is pressed), it has to:
instantiate a new System.Media.SoundPlayer
load the sound file into teeth1_Sound
play the sound file with the Play() method
You might find there is a delay each time as the code re-instantiates teeth1_Sound and reloads the sound file? It might be easier to load all the sound files when the app is starting up, have them ready to Play() as soon as you need them?

C# windows forms How to play audio on webbrowser controller?

I prefer to use wavesurfer.js player in my web browser controller in C#.
The problem is wavesurfer isn't loading file.
Sample player is http://mypublic.kissr.com/
I am on windows forms applicaton. I tried with default webbrowser controller it didn't work.
then I tried with CefSharp browser controller. It still didn't work.
Any help is greatly appreciated.
Data View Waves Timer and Pointer location all these are important to me. that's why I need to use wavesurfer.
The link below, gives a very good tutorial, about playing mp3 files from a windows form with c#:
http://www.daniweb.com/software-development/csharp/threads/292695/playing-mp3-in-c
This link will lead you to a topic, which contains a lot information about how to play an mp3 song, using Windows forms. It also contains a lot of other projects, trying to achieve the same thing:
http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/3dbfb9a3-4e14-41d1-afbb-1790420706fe
For example use this code for .mp3:
WMPLib.WindowsMediaPlayer wplayer = new WMPLib.WindowsMediaPlayer();
wplayer.URL = "My MP3 file.mp3";
wplayer.Controls.Play();
Then only put the wplayer.Controls.Play(); in the Button_Click event.
For example use this code for .wav:
System.Media.SoundPlayer player = new System.Media.SoundPlayer();
player.SoundLocation = "Sound.wav";
player.Play();
Put the player.Play(); in the Button_Click event, and it will work.

Keyboard shortcuts to trigger context menus

I am working on a C# application which consists of some context menus that have an ability to communicate with my website via WebClient(). The options work when they are clicked.
Once my app is opened, it stays open in the tray and it doesn't show in the taskbar/toolbar (the bar in the bottom where open programs stay). It's basically a background application that runs continuously.
There is a section in the context menu named Upload which includes Upload from Computer and Window screenshot. These are the two items that I want to be accessed via keyboard shortcuts. It shouldn't matter where the user is, once he clicks the set keyboard keys, he will trigger the application's _Click event for a certain context menu.
Final question: How do I make global keyboard shortcuts to trigger some context menus item _Click event?
It would be good is someone could explain a bit more broadly how to achieve this. I'm into C# for a short time (1 month learning it, 2 weeks using it) and I am having trouble understanding code just pasted here.
This is one of the click events I want to associate with a keyboard shortcut:
private void menu_upload_file_Click(object sender, EventArgs e)
{
DialogResult dialogOpened = openFileDialog1.ShowDialog();
if (dialogOpened == DialogResult.OK)
{
string filename = openFileDialog1.FileName;
this.sendToIMGit(filename);
}
}
Thanks.
You will need to use a 'keyboard hook' to create a global hotkey.
See this question.

How to play background music online in Windows 8

In my application, I use UI MediaElement. But when i click the Windows key, the music stops.
I tried using:
MediaControl.PlayPressed += MediaControl_PlayPressed;
MediaControl.PausePressed += MediaControl_PausePressed;
MediaControl.PlayPauseTogglePressed += MediaControl_PlayPauseTogglePressed;
MediaControl.StopPressed += MediaControl_StopPressed;
I set source MediaElement:
media.Source = new Uri("http://stream-hq.mp3.zdn.vn/fsgggsfdlwjglwjAAAAA/2a3f830202ea6d29bc7c5a5146401566/4ff5620a/2011/12/27/a/4/a4fcc199a184a93cfeb0fe35642c53bf.mp3", UriKind.RelativeOrAbsolute);
Please help me!
For a Metro/WinRT app to play audio in background, the app needs the following:
A MediaElement control that:
Is in a XAML page.
The AudioCategory property set to BackgroundCapableMedia (as in Armando's answer). There are other values for games or communication systems as needed. See the Audio Playback in a Metro Application for information on what the different options mean.
Use the MediaControl object to capture at least the following. Other events and properties can be handled if desired but the following are required for background playback to function.
PlayPressed
StopPressed
PlayPauseTogglePressed
PausePressed
Add audio to the list of support background tasks in the applications manifest. The manifest is usually called Package.appxmanifest. Select it in the Solution Explorer, go to the Declarations tab and check "Audio" as shown:
See the Transport Controls Guide for more info about capturing hardware buttons (e.g. play/pause on the keyboard) and the quickstart guide for creating a media player for more info.
This would be my first answer. Make sure you set AudioCategory="BackgroundCapableMedia" in your XAML like this:
<MediaElement x:Name="backgroundMusic"
AutoPlay="True"
AudioCategory="BackgroundCapableMedia"
Source="mms://betafm.santafe-conicet.gov.ar:1175">
</MediaElement>
Hope it helps!

How can i use MEF to partition my project into smaller xap and download them on the fly?

Right now, my XAP file has become big and i need a solution to partition it into some smaller applications. MEF or PRISM might fix my problem
I read and watch online tutorial for them but still have no clue how i can apply them to my current project.
Let me explain my project:
-In the mainpage.xaml, it only has ONE menucontrol . However, that menucontrol will be built DYnamically basing on the data retrieved through the service call. You can see on my Menu picture
http://www.flickr.com/photos/31396433#N08/sets/72157627077751863/
-Everytime a user click on a menuItem, a window of that menuItem will be pop-up to let the user doing business work. You can see on my GeneralLedger_JournalPosting picture. The journalPosting menuItem belong to the GeneralLedger section.
http://www.flickr.com/photos/31396433#N08/sets/72157627077751863/
This is the code of showing how i show the pop-up menuItem window through the click event of the menuItem on the menuControl
private void MenuItemClick(object sender, RadRoutedEventArgs args)
{
RadMenuItem item = args.OriginalSource as RadMenuItem;
SFMenu sFMenu = item.Header as SFMenu;
OpenMenuItemScreenBy(sFMenu.Name);
}
private void OpenMenuItemScreenBy(string menuName)
{
if (menuName == "User Management")
{
var userManagement = new UserManagement();
//userManagement.WindowStartupLocation = WindowStartupLocation.Manual;
userManagement.Top = 50;
userManagement.Show();
}
//Testing area
else if (menuName == "Testing")
{
Testing t = new Testing();
t.Top = 50;
t.Show();
}
//
......
.......
That's all about my project. Basically, i just need to create different screen for each of my menuItem. Because the number of my menuItems continue to increase so the more corresponding window screen should be created. And that makes my XAP become bigger.
Solution:
I am thinking a way to seperate each of my Window MenuItem screen (such as the GeneralLedger_JournalPosting) into seperate XAP. And my main XAP file will only contains the menuControl.
However, I need to know a way how to load my corresponding menuItem XAP file on the fly if the user click on a menuItem(for example GeneralLedger / JournalPosting). And open the JournalPosting screen
But if the user click on that menuItem again, then no download needed. Just look at on the cache
(I watch MEF tutorial and know that i need to use the DeloymentCatalog for the feature. However, i don't see any example to let us manually access through code the usercontrol in the dynamic XAP file)
Secondly,
Because each of my menuItem window screen will use the same third-party dll (for example: the dll for the GridView, Navigation,...). So can you also tell me how to let me only download those dll ONE time . Because if i put those dll into each of my menuItem window screen XAP, then i think they will be redownloaded every time the corresponding XAP requested for downloading
thank you for your help.
have a look here: http://www.codeproject.com/KB/silverlight/MEFDynamicLoading.aspx. This project describes how to load xap's on demand and displaying them after downloading.
The interesting part for you is the MainPageModel.cs. There is the loading of the xap and putting the content into the panel.So if you ask the DeploymentCatalogService to "AddXap" and it is already loaded => call the callback or fire the event.
Regarding the dll's. You have to put them in your MainApp. In you downloaded app's you have to set the in the MainApp defined dll's to CopyLocal = false (It is found in the Properties of the dll (References))
I hope this helps!
BR,
TJ

Categories

Resources