Search code examples
c#vb.netdirectxdirectsound

Play background music with DirectSound


I'm using DirecSound to play sounds in my app because I need it to be able to play multiple sounds at the same time. However, when I alt-tab or even click on any other window the sound stops playing. Can I make it play in the background, even if the app has not focus?

The code I'm using is basically this:

Dim soundDevice As New Device
soundDevice.SetCooperativeLevel(Me.Handle, CooperativeLevel.Normal)
Dim sb As New SecondaryBuffer(My.Resources.ResourceManager.GetStream("MyFile.wav"), soundDevice)
sb.play(0, BufferPlayFlags.Default)

Solution

  • Oh, thank you so much @user3560941 for answering my question with another question :) (https://stackoverflow.com/questions/23223028/change-directsound-behavior)

    The answer is to create a BufferDescription and set its flags to DSBCAPS_GLOBALFOCUS:

    Dim soundDevice As New Device
    soundDevice.SetCooperativeLevel(Me.Handle, CooperativeLevel.Normal)
    Dim bd As New BufferDescription
    bd.Flags = BufferDescriptionFlags.GlobalFocus
    Dim sb As New SecondaryBuffer(My.Resources.ResourceManager.GetStream("MyFile.wav"), bd, soundDevice)
    sb.play(0, BufferPlayFlags.Default)