Play Sounds in a Visual Studio Application - c#

I'm making a program in Visual Studio 2015 (C#) and I want to add sound effects to it. However, I have looked up countless tutorials but none of them seem to work, and gave me tons of errors. If anyone can give me a code to play a .wav file from resource files then I would be very grateful

How to: Play Sounds in an Application
Add the following method code under the button1_Click event hander :
System.Media.SoundPlayer player =
new System.Media.SoundPlayer();
player.SoundLocation = #"C:\Users\Public\Music\Sample Music\xxxx.wav";
player.Load();
player.Play();

If the file you want to play is wav files, try this.
var player = new System.Media.SoundPlayer("c:\\tes.wav");
player.Play();

For myself I wrote this SounceController, hope it help:
using System.Windows.Media; // add reference to system.windows.presentation.
using System;
using System.IO;
public class SoundController
{
private bool isPlaying;
private MediaPlayer player;
public SoundController()
{
player = new MediaPlayer();
}
~SoundController()
{
player = null;
}
public void Play(string path)
{
if (!File.Exists(path) || isPlaying)
return;
isPlaying = true;
player.Open(new Uri(path));
player.Play();
}
public void Stop()
{
if (isPlaying)
{
isPlaying = false;
player.Stop();
}
}
}

I recommend you use PInvoke To play sound using winmm.dll
first of all import System.Runtime.InteropServices namespace in to your project.
using System.Runtime.InteropServices;
Then in your class you will have
[DllImport("winmm.dll")]
static extern Int32 mciSendString(string command, StringBuilder buffer, int bufferSize, IntPtr hwndCallback);
public void Play(string path ,string name)
{
// Open
mciSendString($#"open {path} type waveaudio alias {name}", null, 0, IntPtr.Zero);
// Play
mciSendString($#"play {name}", null, 0, IntPtr.Zero);
}
You can play the sound sending correct path of wave file with name. . given name does not need to be the same name of wave file.for example:
Play(#"C:\soundeffect.wav", "soundEffect1");
Usually sound effects are played simultaneously. you can call this method several times to play several files simultaneously.
Play(#"C:\soundeffect1.wav", "soundEffect1");
Play(#"C:\soundeffect2.wav", "soundEffect2");
Play(#"C:\soundeffect3.wav", "soundEffect3");

Related

SoundPlayer adjustable volume

I have a class Sounds.cs that manages playing sounds in my form, and I want to be able to adjust the volume to decimal value. Is there a way to change the volume of a sound being played with a SoundPlayer object? Or is there perhaps a different way to play sound that makes this possible?
Unfortunately SoundPlayer doesn't provide an API for changing the volume. You could use the MediaPlayer class:
using System.Windows.Media;
public class Sound
{
private MediaPlayer m_mediaPlayer;
public void Play(string filename)
{
m_mediaPlayer = new MediaPlayer();
m_mediaPlayer.Open(new Uri(filename));
m_mediaPlayer.Play();
}
// `volume` is assumed to be between 0 and 100.
public void SetVolume(int volume)
{
// MediaPlayer volume is a float value between 0 and 1.
m_mediaPlayer.Volume = volume / 100.0f;
}
}
You'll also need to add references to the PresentationCore and WindowsBase assemblies.

How Can I Play Asynchronously Sound Effects In WP8?

I have an instrument application that running with XNA Sound Effect. My problem is that;
When I play a sound effect while another one is playing, the last one is killing the first one. It is not what I want, I want to play sounds asynchronously even they are the same sounds too. What can I do about it?
Thanks for your help.
public static SoundEffectInstance passSound;
public static SoundEffect passSound;
LoadSoundInstance("Assets/SoundEffects/passSound.wav", out passSound, out passSoundInstance);
private void LoadSound(String SoundFilePath, out SoundEffect Sound)
{
// For error checking, assume we'll fail to load the file.
Sound = null;
try
{
// Holds informations about a file stream.
StreamResourceInfo SoundFileInfo = App.GetResourceStream(new Uri(SoundFilePath, UriKind.Relative));
// Create the SoundEffect from the Stream
Sound = SoundEffect.FromStream(SoundFileInfo.Stream);
}
catch (NullReferenceException)
{
// Display an error message
MessageBox.Show("Couldn't load sound " + SoundFilePath);
}
}
private void LoadSoundInstance(String SoundFilePath, out SoundEffect Sound, out SoundEffectInstance SoundInstance)
{
// For error checking, assume we'll fail to load the file.
Sound = null;
SoundInstance = null;
try
{
LoadSound(SoundFilePath, out Sound);
SoundInstance = Sound.CreateInstance();
}
catch (NullReferenceException)
{
// Display an error message
MessageBox.Show("Couldn't load sound instance " + SoundFilePath);
}
}
I am using it with only play;
public void PlaySound(SoundEffectInstance sound)
{
sound.Play();
}
If I call PlaySound method while the same sound is playing it is not play the new one.

How do I figure out if Windows is currently playing any sounds?

How can I figure out if Windows is currently playing any sounds through the primary audio device? I need to know, so that I can make my program automatically adjust its volume.
You could use CSCore.
Download it right here -> http://cscore.codeplex.com/
Paste these lines on a console project.
using System;
using CSCore.CoreAudioAPI;
namespace AudioDetector
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(IsAudioPlaying(GetDefaultRenderDevice()));
Console.ReadLine();
}
public static MMDevice GetDefaultRenderDevice()
{
using (var enumerator = new MMDeviceEnumerator())
{
return enumerator.GetDefaultAudioEndpoint(DataFlow.Render, Role.Console);
}
}
public static bool IsAudioPlaying(MMDevice device)
{
using (var meter = AudioMeterInformation.FromDevice(device))
{
return meter.PeakValue > 0;
}
}
}
}
Play a music be it on YouTube, Music Player, etc...
Run the program.
It automatically notifies(true/false) if there is an audio currently being played or not.
You may need to mess around with mixer controls.
Mixer Control
These may help ya out too.
Measure speaker volume by recording playing sound with microphone
Using p/invoke and win-api to monitor audio line-in (C#)

Play two sounds simultaneusly

Is there a way to play two sounds at the same time?
I know that SoundPlayer isn't able to do this.
I can't use SoundEffect as I believe it's only part of XNA.
The two required sounds will be called at unknown and random times. The sound needs to be be controlled after it is played. i.e., the sound must be able to be stopped before it has finished playing.
Reference PresentationCore and WindowsBase and try this...
var p1 = new System.Windows.Media.MediaPlayer();
p1.Open(new System.Uri(#"C:\windows\media\tada.wav"));
p1.Play();
// this sleep is here just so you can distinguish the two sounds playing simultaneously
System.Threading.Thread.Sleep(500);
var p2 = new System.Windows.Media.MediaPlayer();
p2.Open(new System.Uri(#"C:\windows\media\tada.wav"));
p2.Play();
EDIT
I received a downvote probably because at first glance this looks like it will play the second sound after the first is finished. It doesn't, they are played by windows asynchronously. The sleep is there so if you test this code verbatim you can hear the sounds play together, it wouldn't be noticeable without the delay since they are the same sound.
This code demonstrates the two sounds playing on separate threads on top of each other, which is sort of pointless since the playback doesn't block anyway
new System.Threading.Thread(() => {
var c = new System.Windows.Media.MediaPlayer();
c.Open(new System.Uri(#"C:\windows\media\tada.wav"));
c.Play();
}).Start();
System.Threading.Thread.Sleep(500);
new System.Threading.Thread(() => {
var c = new System.Windows.Media.MediaPlayer();
c.Open(new System.Uri(#"C:\windows\media\tada.wav"));
c.Play();
}).Start();
http://msdn.microsoft.com/en-us/library/system.windows.media.mediaplayer.stop.aspx
The class also has the control you need to stop playback
The "MediaPlayer" object will not let you play two sounds at once, even if you create two instances. You will need to bring in the native windows API "mciSendString".
[DllImport("winmm.dll")]
static extern Int32 mciSendString(string command, StringBuilder buffer, int bufferSize, IntPtr hwndCallback);
public Form1()
{
InitializeComponent();
mciSendString(#"open C:\Users\Jono\Desktop\applause.wav type waveaudio alias applause", null, 0, IntPtr.Zero);
mciSendString(#"play applause", null, 0, IntPtr.Zero);
mciSendString(#"open C:\Users\Jono\Desktop\foghorn.wav type waveaudio alias foghorn", null, 0, IntPtr.Zero);
mciSendString(#"play foghorn", null, 0, IntPtr.Zero);
}
check PlaySound method here http://msdn.microsoft.com/en-us/library/aa909766.aspx, and its flag SND_ASYNC .
Solution :
Hi,
I was developing a WP8 App and i needed multiple sounds to play simultaneously, the solutions mentioned above didnt work for me, So i used the XNA framwork. here is the link
http://msdn.microsoft.com/en-us/library/ff842408.aspx
and then play ur sound files like this...
SoundEffect Sound = SoundEffect.FromStream(Application.GetResourceStream(new Uri("Assets/Sounds/wav/sound.wav", UriKind.Relative)).Stream);
Sound.Play();
For looping...
SoundEffectInstance Sound = SoundEffect.FromStream(Application.GetResourceStream(new Uri("Assets/Sounds/wav/sound.wav", UriKind.Relative)).Stream).CreateInstance();
Sound.IsLooped = true;
Sound.Play();
Note: the files must be in ".wav" (PCM, 8 or 16-bit, 8KHz to 48KHz, mono or stereo) format
From http://alvas.net/alvas.audio,samples.aspx#sample7 and http://alvas.net/alvas.audio,samples.aspx#sample6
Player pl = new Player();
byte[] arr = File.ReadAllBytes(#"in.wav");
pl.Play(arr);
Player pl2 = new Player();
pl2.FileName = "123.mp3";
pl2.Play();
or mix audio data before playing How to mix to mix two audio file..
private void Mix(string outfile, string infile1, string infile2, int shiftSec)
{
WaveReader wr1 = new WaveReader(File.OpenRead(infile1));
WaveReader wr2 = new WaveReader(File.OpenRead(infile2));
IntPtr format1 = wr1.ReadFormat();
WaveFormat wf = AudioCompressionManager.GetWaveFormat(format1);
WaveWriter ww = new WaveWriter(File.Create(outfile), AudioCompressionManager.FormatBytes(format1));
byte[] data0 = wr1.ReadData(0, shiftSec);
byte[] data1 = wr1.ReadData(shiftSec);
byte[] data2 = wr2.ReadData();
byte[] mixData = AudioCompressionManager.Mix(format1, data2, data1);
ww.WriteData(data0);
ww.WriteData(mixData);
ww.Close();
wr2.Close();
wr1.Close();
}
The accepted answer didn't work for me.
Here is what worked:
Make sure you add references to PresentationCore and WindowsBase dlls.
private void Form1_Load(object sender, EventArgs e)
{
System.Media.SoundPlayer player = new System.Media.SoundPlayer(#"C:\Users\me\source\repos\TacticalIslandSurvival\sounds\blazer rail.wav");
player.PlayLooping();
}
private void button1_MouseEnter(object sender, EventArgs e)
{
var p1 = new System.Windows.Media.MediaPlayer();
p1.Open(new System.Uri(#"C:\Users\me\source\repos\TacticalIslandSurvival\sounds\click.wav"));
p1.Play();
}

Change The Volume in System.Media.SoundPlayer

I am using System.Media.SoundPlayer to play some wav files in my project.
Is it possible to change the volume of this SoundPlayer? If there is no way to do that, how can I change the volume of my computer using C#?
From SoundPlayer adjustable volume:
Unfortunately SoundPlayer doesn't provide an API for changing the volume. You could use the MediaPlayer class:
using System.Windows.Media;
public class Sound
{
private MediaPlayer m_mediaPlayer;
public void Play(string filename)
{
m_mediaPlayer = new MediaPlayer();
m_mediaPlayer.Open(new Uri(filename));
m_mediaPlayer.Play();
}
// `volume` is assumed to be between 0 and 100.
public void SetVolume(int volume)
{
// MediaPlayer volume is a float value between 0 and 1.
m_mediaPlayer.Volume = volume / 100.0f;
}
}
You'll also need to add references to the PresentationCore and WindowsBase assemblies.

Categories