上面代码报错 CS1503: 参数 2: 无法从"Microsoft.DirectX.DirectSound.WaveFormat”转换为"int'
时间: 2024-02-16 13:00:07 浏览: 154
这个错误是因为在创建SecondaryBuffer对象时,第二个参数需要传入一个整数值,代表缓冲区的大小,但是你传入了WaveFormat对象。
要解决这个错误,你需要计算出缓冲区的大小,并将其传递给SecondaryBuffer构造函数。可以通过以下方式计算缓冲区的大小:
```csharp
int bufferSize = (int)(memoryStream.Length / ((double)waveFormat.AverageBytesPerSecond / (double)waveFormat.BlockAlign)) * waveFormat.BlockAlign;
```
然后将计算出的bufferSize作为第二个参数传递给SecondaryBuffer构造函数即可。修改后的Speak方法如下:
```csharp
static void Speak(string text, Device device)
{
SpeechSynthesizer speechSynthesizer = new SpeechSynthesizer();
speechSynthesizer.Volume = 100;
speechSynthesizer.Rate = 0;
MemoryStream memoryStream = new MemoryStream();
speechSynthesizer.SetOutputToWaveStream(memoryStream);
speechSynthesizer.Speak(text);
memoryStream.Seek(0, SeekOrigin.Begin);
WaveFormat waveFormat = new WaveFormat();
waveFormat.BitsPerSample = 16;
waveFormat.Channels = 1;
waveFormat.BlockAlign = (short)(waveFormat.Channels * (waveFormat.BitsPerSample / 8));
waveFormat.SamplesPerSecond = 16000;
waveFormat.AverageBytesPerSecond = waveFormat.SamplesPerSecond * waveFormat.BlockAlign;
int bufferSize = (int)(memoryStream.Length / ((double)waveFormat.AverageBytesPerSecond / (double)waveFormat.BlockAlign)) * waveFormat.BlockAlign;
SecondaryBuffer buffer = new SecondaryBuffer(bufferSize, device);
buffer.Write(0, memoryStream, (int)memoryStream.Length, LockFlag.None);
buffer.Play(0, BufferPlayFlags.Default);
}
```
这样就可以正确计算缓冲区大小,并将其传递给SecondaryBuffer构造函数。
阅读全文