Play a sound in a specific device with C#

In your button click handlers you are creating a WaveOut device, setting its device number, and then your playSound function plays sound using a completely different IWavePlayer (an instance of DirectSoundOut). There are several problems with your code as it stands (particularly with concurrent playbacks), but I would start by passing the device number into the playSound function.

public void playSound(int deviceNumber)
{
    disposeWave();// stop previous sounds before starting
    waveReader = new NAudio.Wave.WaveFileReader(fileName);
    var waveOut = new NAudio.Wave.WaveOut();
    waveOut.DeviceNumber = deviceNumber;
    waveOut.Init(waveReader);
    waveOut.Play();
}

I had a similar problem in which I needed to be able to control which sound device to play a sound on and I found a nice library (irrKlang) that makes doing so very easy. For anyone interested, here's the link: http://www.ambiera.com/irrklang/downloads.html. With this library it is only a few lines of code to select your desired sound device and play a sound with it.

//Get the list of installed sound devices. 
sdl = new IrrKlang.ISoundDeviceList(IrrKlang.SoundDeviceListType.PlaybackDevice);

//Add each device to a combo box.
for(int i = 0; i < sdl.DeviceCount; i++)
{
    comboBox1.Items.Add(sdl.getDeviceDescription(i) + "\n");
}


//Place this code in your play sound event handler.
//Create a sound engine for the selected device (uses the ComboBox index to 
//get device ID).
irrKlangEngine = new IrrKlang.ISoundEngine(IrrKlang.SoundOutputDriver.AutoDetect,
                IrrKlang.SoundEngineOptionFlag.DefaultOptions, 
                sdl.getDeviceID(comboBox1.SelectedIndex));

//Play the selected file
playSelectedFile(fileName);

I hope this helps someone.

Tags:

C#