使用DirectSound播放背景音乐

本文关键字:背景音乐 播放 DirectSound 使用 | 更新日期: 2023-09-27 18:21:44

我使用DirecSound在我的应用程序中播放声音,因为我需要它能够同时播放多个声音。然而,当我切换选项卡,甚至点击任何其他窗口时,声音都会停止播放。即使应用程序没有焦点,我也可以让它在后台播放吗?

我使用的代码基本上是这样的:

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)

使用DirectSound播放背景音乐

哦,非常感谢@user3560941用另一个问题回答了我的问题:)(https://stackoverflow.com/questions/23223028/change-directsound-behavior)

答案是创建一个BufferDescription并将其标志设置为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)