The following Code shows how to play a sound.

public void PlayASound()
{
    //Contains the sound to play
    using (IWaveSource soundSource = GetSoundSource())
    {
        //SoundOut implementation which plays the sound
        using (ISoundOut soundOut = GetSoundOut())
        {
            //Tell the SoundOut which sound it has to play
            soundOut.Initialize(soundSource);
            //Play the sound
            soundOut.Play();

            Thread.Sleep(2000);

            //Stop the playback
            soundOut.Stop();
        }
    }
}

private ISoundOut GetSoundOut()
{
    if (WasapiOut.IsSupportedOnCurrentPlatform)
        return new WasapiOut();
    else
        return new DirectSoundOut();
}

private IWaveSource GetSoundSource()
{
    //return any source ... in this example, we'll just play a mp3 file
    return CodecFactory.Instance.GetCodec(@"C:\Temp\sound.mp3");
}

As you can see. There are two components you need to play a sound:

  1. A sound to play (represented by the IWaveSource-interface)
  2. A soundout which plays the sound (represented by the ISoundOut-interface)

In general, it is recommended to use WasapiOut instead of DirectSoundOut. But remember that WasapiOut is only supported since Windows Vista.

Last edited Apr 21, 2014 at 9:25 PM by filoe, version 3

Comments

SuperDave Feb 16, 2015 at 3:15 PM 
VB converted example:

Imports CSCore
Imports CSCore.SoundOut
Imports CSCore.Codecs


Public Class Form1

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click

Using soundSource As IWaveSource = GetSoundSource()
'SoundOut implementation which plays the sound
Using soundOut As ISoundOut = GetSoundOut()
'Tell the SoundOut which sound it has to play
soundOut.Initialize(soundSource)
'Play the sound
soundOut.Play()

System.Threading.Thread.Sleep(5000)

'Stop the playback
soundOut.[Stop]()
End Using
End Using

End Sub

Private Function GetSoundOut() As ISoundOut

If WasapiOut.IsSupportedOnCurrentPlatform Then
Return New WasapiOut()
Else
Return New DirectSoundOut()
End If

End Function

Private Function GetSoundSource() As IWaveSource

'return any source ... in this example, we'll just play a mp3 file
Return CodecFactory.Instance.GetCodec("D:\audioclips\AnimalHouse\worthless.mp3")

End Function

End Class

zecarlosalmeida Sep 18, 2014 at 9:57 PM 
Works fine, I have to add the CSCore.SoundOut, CSCore.Codecs.