开发者

Changing wave format at runtime with NAudio

开发者 https://www.devze.com 2023-03-22 11:02 出处:网络
I have initialized the device using: staticIWavePlayerwaveOut; staticWaveFormatwaveFormat; staticBufferedWaveProviderwaveProvider;

I have initialized the device using:

static  IWavePlayer     waveOut;
static  WaveFormat      waveFormat;
static  BufferedWaveProvider    waveProvider;

private static int AudioDeviceInit()
{
            waveOut = new DirectSoundOut();
            waveFormat = new WaveFormat(44100, 2);
            waveProvider = new BufferedWaveProvider(waveFormat);

            waveOut.Init(waveProvider);
            waveOut.Play();

            return 0;
}

I am adding pcm stream to it using:

waveProvider.AddSamples(samples, 0, size);

The above is workin开发者_运维百科g fine as long as the stream data is of the same configuration.

I have another function that receives sample rate and number of channels and I want to reconfigure the waveprovider to use the newly provided configuration. Here is the code that I am using:

private static void AudioConfigCallback(int rate, int channel)
{
    waveFormat = new WaveFormat(rate, channel);
    waveProvider = new BufferedWaveProvider(waveFormat);
    waveOut.Init(waveProvider);
    return;
}

This is not working and I believe that this is not the correct way of doing it as well. Any idea how I can reconfigure the device to use new sample_rate and num_channels

Thanks.


This is not possible. When you open an output device, whether WaveOut, Direct Sound, WASAPI or ASIO, at that point you must specify the format at which you will work. You must close the output device and re-open it with the new WaveFormat.

An alternative approach would be to always convert to a fixed WaveFormat, and use WaveFormatConversionStream to convert to the correct format whenever the incoming format changes. This would allow you to avoid opening and closing the output device.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号