AlreadyAllocated calling waveOutOpen error

谁都会走 提交于 2019-11-29 07:48:49

You are constantly creating WaveOut objects inside your while loop that are not disposed, which is part of the issue. The best approach in this situation is to create a single WaveOut object and to feed it using a BufferedWaveProvider. Then as audio becomes available, write it into the BufferedWaveProvider.

I was facing a similar problem when initializing new WaveOut objects with SineWaveProviders. I came across the idea of using something like a ringlist to swap the different provider's values (frequency and amplitude) as, at least in my case, I couldn't hear any difference above 5 constant sine waves. Furthermore, in my tests on different machines, using more than 6-7 WaveOut objects at once usually resulted in MemoryAllocationErrors thus the ringlist. This is, what I came out with:

private Queue<SineWaveGenerator> generators;

// constructor
public Player()
{
    for (int i = 0; i < 5; i++)
    {
        var generator = new SineWaveGenerator();
        generator.Amplitude = 0.25f;

        generators.Enqueue(generator);
    }
}

// just a helper method
private SineWaveGenerator GetGenerator(int frequency)
{
    return generators.FirstOrDefault(x => x.Frequency == frequency);
}

private void Play(int frequency)
{
    var generator = GetGenerator(frequency);

    if (generator == null)
    {
        generator = generators.Dequeue(); // get generator from the top of the list
        generator.Frequency = GetFrequency(key); // modify the generator
        generators.Enqueue(generator); // and append it to the back
    }

    generator.Play();
}

private void Stop(int frequency)
{
    var generator = GetGenerator(frequency);

    if (generator != null)
    {
        generator.Stop();
    }
}

Note: The SineWaveGenerator initializes a new WaveOut in its constructor.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!