我的directx声音缓冲区有静电噪声

时间:2016-12-01 21:43:46

标签: c# directx sharpdx directsound

所以我喜欢从事大学任务(保持我的一些技能),我决定解决这个问题:

http://introcs.cs.princeton.edu/java/assignments/dsp.html

我正在运行MSVS2015 C#/ Console应用程序以及SharpDX程序包,这使我可以访问一些基础DirectSound功能。我只是想在第一个例子中创建并播放2秒音符'A'。当我运行以下代码时,它会播放2秒,但它非常静态。我假设我的计算中有一些东西,但我无法弄清楚到底是什么。有没有人有写自己的数字声音缓冲区的经验?

谢谢, - 杰夫

public class Execution : IDisposable
{
    IntPtr Handle;
    DirectSound Device;
    SecondarySoundBuffer Buffer;
 
    public Execution()
    {
        Handle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
 
        Device = new DirectSound();
        Device.SetCooperativeLevel(Handle, CooperativeLevel.Priority);
 
        var rate = 44100;
        var bits = 16;
        var channels = 1;
        var waveFormat = new WaveFormat(rate, bits, channels);
 
        // Create a buffer with 2 seconds of sample data
        var seconds = 2;
 
        var bufferDescription = new SoundBufferDescription() { Format = waveFormat, BufferBytes = waveFormat.AverageBytesPerSecond * seconds };
        Buffer = new SecondarySoundBuffer(Device, bufferDescription);
 
        var noteFrequency = 440f;       // A
        var bufferData = new float[bufferDescription.BufferBytes];
 
        var count = 0;
        for (var sample = 0; sample < bufferDescription.BufferBytes; sample++)
        {
            var sampleInSeconds = (float)sample / (float)bufferDescription.BufferBytes * (float)seconds;
            var value = (float)Math.Sin(2f * Math.PI * noteFrequency * sampleInSeconds );
            bufferData[sample] = value;
        }
 
        Buffer.Write(bufferData, 0, LockFlags.EntireBuffer);
    }
 
    public void Execute()
    {
        Buffer.Play(0, 0);
    }
 
    public void Dispose()
    {
        Buffer.Dispose();
        Device.Dispose();
    }
}

1 个答案:

答案 0 :(得分:0)

由于var bits = 16;预期值应为短(-32768,+ 32767),因此只需将bufferData替换为new short[bufferDescription.BufferBytes];,最终计算bufferData[sample] = (short)(value * short.MaxValue);应该可以修复噪音