4
(道歉,如果这是一个重复的...我张贴,但并没有发现它实际上是由它来论坛)播放声音与SlimDX和DirectSound的(C#)
我一直试图让SlimDX的DirectSound加工。这是我的代码。它从一个wav文件填充二级缓冲区,然后在一个线程循环中交替地填充缓冲区的下半部分或上半部分。
它播放缓冲区罚款的第一个负载。 AutoResetEvents在它们应该和下半部分然后填充上半部分时触发(用Debug语句验证)。但是在第一次加载缓冲区后播放不会继续。所以不知怎的,缓冲区的重新填充不能正常工作。
想法?
(我用的DirectSound,因为它是我发现设置,我想使用的音频设备的GUID的唯一途径。愿意接受其他.NET友好的方式。)
private void PlaySound(Guid soundCardGuid, string audioFile) { DirectSound ds = new DirectSound(soundCardGuid); ds.SetCooperativeLevel(this.Handle, CooperativeLevel.Priority); WaveFormat format = new WaveFormat(); format.BitsPerSample = 16; format.BlockAlignment = 4; format.Channels = 2; format.FormatTag = WaveFormatTag.Pcm; format.SamplesPerSecond = 44100; format.AverageBytesPerSecond = format.SamplesPerSecond * format.BlockAlignment; SoundBufferDescription desc = new SoundBufferDescription(); desc.Format = format; desc.Flags = BufferFlags.GlobalFocus; desc.SizeInBytes = 8 * format.AverageBytesPerSecond; PrimarySoundBuffer pBuffer = new PrimarySoundBuffer(ds, desc); SoundBufferDescription desc2 = new SoundBufferDescription(); desc2.Format = format; desc2.Flags = BufferFlags.GlobalFocus | BufferFlags.ControlPositionNotify | BufferFlags.GetCurrentPosition2; desc2.SizeInBytes = 8 * format.AverageBytesPerSecond; SecondarySoundBuffer sBuffer1 = new SecondarySoundBuffer(ds, desc2); NotificationPosition[] notifications = new NotificationPosition[2]; notifications[0].Offset = desc2.SizeInBytes/2 + 1; notifications[1].Offset = desc2.SizeInBytes - 1; ; notifications[0].Event = new AutoResetEvent(false); notifications[1].Event = new AutoResetEvent(false); sBuffer1.SetNotificationPositions(notifications); byte[] bytes1 = new byte[desc2.SizeInBytes/2]; byte[] bytes2 = new byte[desc2.SizeInBytes]; Stream stream = File.Open(audioFile, FileMode.Open); Thread fillBuffer = new Thread(() => { int readNumber = 1; int bytesRead; bytesRead = stream.Read(bytes2, 0, desc2.SizeInBytes); sBuffer1.Write<byte>(bytes2, 0, LockFlags.None); sBuffer1.Play(0, PlayFlags.None); while (true) { if (bytesRead == 0) { break; } notifications[0].Event.WaitOne(); bytesRead = stream.Read(bytes1, 0, bytes1.Length); sBuffer1.Write<byte>(bytes1, 0, LockFlags.None); if (bytesRead == 0) { break; } notifications[1].Event.WaitOne(); bytesRead = stream.Read(bytes1, 0, bytes1.Length); sBuffer1.Write<byte>(bytes1, desc2.SizeInBytes/2, LockFlags.None); } stream.Close(); stream.Dispose(); }); fillBuffer.Start(); } }
谢谢。就是这样。在没有任何关于这个主题的SlimDX文档的时候,我误解了这些标志的含义。 – blearyeye 2010-10-07 18:19:04
完成。忘了这么做了。 – blearyeye 2011-01-06 20:16:15
也适用于DirectSound。与blearyeye有同样的问题。感谢您指点我... – 2011-02-15 10:48:06