DirectSound: “Value does not fall within the expected range.” when initializing Notify
-
21-01-2021 - |
题
I'm getting that exception when I try to run a simple DirectSound program. Here's the code:
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.DirectX.DirectSound;
namespace AudioDemo
{
class Program
{
[DllImport("user32.dll")]
private static extern IntPtr GetDesktopWindow();
static void Main(string[] args)
{
// output device
var device = new Device();
device.SetCooperativeLevel(GetDesktopWindow(), CooperativeLevel.Normal);
// format description
var format = new WaveFormat
{
BitsPerSample = 8,
Channels = 1,
FormatTag = WaveFormatTag.Pcm,
SamplesPerSecond = 8000
};
format.BlockAlign = (short)(format.BitsPerSample / 8 * format.Channels);
format.AverageBytesPerSecond = format.SamplesPerSecond * format.BlockAlign;
var outputLatency = 20;
var frameSize = format.AverageBytesPerSecond * outputLatency / 1000;
// buffer
var description = new BufferDescription
{
BufferBytes = frameSize,
Format = format,
DeferLocation = true,
GlobalFocus = true
};
var outputBuffer = new SecondaryBuffer(description, device);
// buffer notifications
var notify = new Notify(outputBuffer);
// ...
}
}
}
I get the exception on the last line (var notify = new Notify(outputBuffer);
).
Not sure what went wrong. The buffer was initialized correctly.
解决方案
It's not clear to me what you're trying to do with your outputLatency
and frameSize
variables, or with the BufferBytes
property, but my guess is there is where your problem is.
其他提示
"A SecondaryBuffer object will support notification events only if its BufferDescription.ControlPositionNotify
is set to true
."
(https://msdn.microsoft.com/en-us/library/windows/desktop/ms812460.aspx)
So try this:
var description = new BufferDescription
{
BufferBytes = frameSize,
Format = format,
DeferLocation = true,
GlobalFocus = true,
ControlPositionNotify = true
};
I've had the same exception, but this solved the problem!
不隶属于 StackOverflow