Adding sound effects to WPF Surface application - c#

I am trying to play a sound whenever an object is touched/moved in my WPF Surface application, to depict it has been selected or its movement. Here is what I tried but it doesn't seem to work.
SoundPlayerAction soundPlayerAction = new SoundPlayerAction();
soundPlayerAction.Source = new Uri(#"C:\Resources\Selection.wav", UriKind.RelativeOrAbsolute);
EventTrigger eventTrigger = new EventTrigger(TouchEnterEvent); // this is the event you want to trigger the sound effect.
eventTrigger.Actions.Add(soundPlayerAction);
Any feedback or ideas will be much appreciated.

Create a new folder in your project and rename it to SOUNDS then insert your sound files in it and try this:
SoundPlayerAction soundPlayerAction = new SoundPlayerAction();
soundPlayerAction.Source = new Uri(#"SOUNDS\Selection.wav", UriKind.RelativeOrAbsolute);
EventTrigger eventTrigger = new EventTrigger(TouchEnterEvent); // this is the event you want to trigger the sound effect.
eventTrigger.Actions.Add(soundPlayerAction);
Triggers.Add(eventTrigger); // Add this event trigger to Window.Triggers collection.

C:\Resources\Selection.wav is obviously not the correct path of the sound file.
You should create a folder named "Resources" in your Visual Studio project, and add the sound file to that folder. Then go to the properties of the sound file and set its Build Action to Resource and also set Copy to Output Directory to Copy aways or Copy if newer.
Now you can access the file by a relative Uri like this:
soundPlayerAction.Source = new Uri("Resources/Selection.wav", UriKind.Relative);

I came across this link https://www.youtube.com/watch?v=nF-HYoTurc8 and somewhat changed my code and the sound worked :D
In my PreviewTouchDown method, I added:
SoundPlayer soundPlayerAction = new SoundPlayer(TangramsTool.Properties.Resources.Selection);
soundPlayerAction.Play();

Related

WPF Application Relative path to a mp3 sound file

I'm building a WPF project with Visual Studio 2012 and I'm finding a problem with relative paths.
In the specific, I want a sound to be played when a ToggleButton is checked.
This is the code for my button:
<ToggleButton Name="Circles" Margin="88,104,86,172" Background="#FFFFD0CD" Foreground="Black" Checked="Circles_Checked">Circles</ToggleButton>
and if I write like this:
private void Circles_Checked(object sender, System.Windows.RoutedEventArgs e)
{
MediaPlayer mplayer = new MediaPlayer();
mplayer.Open(new Uri("C:\\Users\\user1\\Documents\\Visual Studio 2012\\Projects\\RehabilitationGUIProject\\RehabilitationGUIProject\\circles.mp3", UriKind.Relative));
mplayer.Play();
}
everything works as espected. But I want this code to work also onto other machines, not only mine. And what If I have to move the sounds to another location? I would like to use relative paths and move every sound inside my project folder.
So I created a new folder named Sound inside my root project, the structure is like this:
RehabilitationGuiProject
\Properties
\References
\Bin
\Object
\Sounds
\circles.mp3
... other files .xaml
So I wrote the same lines of code above, changing this one:
mplayer.Open(new Uri(#"/Sounds/circles.mp3", UriKind.Relative));
But no sound is played. Which is the correct relative path for playing sounds from a project folder?
The path must be relative to the folder where your application is executed.
mplayer.Open(new Uri(#"../../Sounds/circles.mp3", UriKind.Relative));
(Assuming your exe is run from the Bin/Debug folder)

Can't play mp3 with MediaElement on WP7 emulator

I have an app where I have some prerecorded text to speech (As there is no default support for text to speech) then I want to play them like this
var mediaElement = new MediaElement();
mediaElement.Source = new Uri("sound.mp3", UriKind.Relative);
mediaElement.Position = new TimeSpan(0);
mediaElement.Play();
But nothing happens, do I HAVE to create a "real" control in my UI? I just want to play this sound when an event happens, I get no errors or nothing, nomatter if the mp3 is in the default folder or not.
The reason it's not playing is because you haven't added it to the Visual Tree. When you create a MediaElement programmatically, it needs to be added somewhere in the tree. You'll have to create a 'real control' in your UI, but it doesn't have to be seen.
var mediaElement = new MediaElement();
mediaElement.Source = new Uri("sound.mp3", UriKind.Relative);
mediaElement.Position = new TimeSpan(0);
LayoutRoot.Children.Add(mediaElement); //Add to visual tree
mediaElement.Play();
This depends on what happens in your code after mediaElement is declared. Currently, as soon as the method you declare it in ends, mediaElement will fall out of scope and become eligible for garbage collection.
You need to either:
Parent mediaElement to something, perhaps your UI
Make mediaElement a static field on the class
All that said, is playing through MediaElement supported in the Emulator?

Playing same sound many times C# WPF

I'm trying to play the same overlapping sound whenever a button is pressed.
I tried with MediaElement and SoundPlayer, but the music stops and starts again. I need to create a new instance, but creating new MediaElement() and adding to the Stage didn´t work too :-/
Thanks for your help
Check here: http://www.interact-sw.co.uk/iangblog/2008/01/25/wpf-concurrent-audio
Create multiple MediaPlayers in the CodeBehind.
I had no succeed with MediaPlayers, but it works:
MediaElement mp = new MediaElement();
soundPanel.Children.Add(mp);
mp.Source = new Uri(key_sound, UriKind.RelativeOrAbsolute);

How to play a sound in C#, .NET

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.

Playing mp3 in WPF

MediaElement doesnt work for me in my WPF application.
mediaElement1.LoadedBehavior = MediaState.Manual;
mediaElement1.Source = new Uri(#"C:\Music\MySong.mp3", UriKind.RelativeOrAbsolute);
mediaElement1.Play();
When I do this in my Window1.xaml.cs file. Nothing happens. Atleast I cant hear anything. I have tried all kind of different things, but no sound.
In winforms:
axWindowsMediaPlayer1.URL = #"C:\Music\MySong.mp3";
axWindowsMediaPlayer1.Ctlcontrols.play();
Works without any problems. Any simple solution or things to try?
Ok I solved it. WPF only support MediaElement if you have Windows Media Player 10 or above. I was running WMP9.
Though I'm also new in wpf,One thing you should notice about media element is that providing source in the XAML tag is not worth working.
you need to provide the source with the urikind like this
media.Source = new Uri(#"E:\Pehli_Baar_Mohabbat.mp3",UriKind.RelativeOrAbsolute);
put this line in window constructor
and set loadedbehavious=manual and then check.
mediaElement1.LoadedBehavior = MediaState.Manual;
---- edit to-----
mediaElement1.LoadedBehavior = System.Windows.Controls.MediaState.Manual;

Categories

Resources