0

I've written a method in C# using NAudio that successfully outputs 2 channel sound, but fails at 6 channel sound.

When using WaveOut, I get 'MmException was unhandled: InvalidParameter calling waveOutOpen'

Here's my code:

    public class AudioOutput {
    private WaveOut latestAudioOut = null;
    private WaveMemoryStream latestMemoryStream = null;
    public void PlayAudio (byte[][] buffers, WaveFormat format) {
        if (latestAudioOut != null) {
            latestAudioOut.Stop();
            latestAudioOut.Dispose();
        }
        latestAudioOut = new WaveOut();
        if (latestMemoryStream != null) {
            latestMemoryStream.Dispose();
        }
        int longestChannelLength = 0;
        foreach (byte[] b in buffers) {
            if (b != null) if (b.Length > longestChannelLength) longestChannelLength = b.Length;
        }
        byte[][] finalisedbuffers = new byte[buffers.Length][];
        for (int i = 0; i < buffers.Length; i ++) {
            finalisedbuffers[i] = new byte[longestChannelLength];
            if (buffers[i] != null) buffers[i].CopyTo(finalisedbuffers[i], 0);
        }
        buffers = finalisedbuffers;
        byte[] interLeavedBuffer = new byte[longestChannelLength * buffers.Length];
        int bytesPerSample  = format.BitsPerSample / 8;
        int frameLength = buffers.Length * bytesPerSample;
        int numberOfFrames = longestChannelLength / bytesPerSample;
        int position = 0;
        int frameStart = 0;
        for (int f = 0; f < numberOfFrames; f ++) {
            for (int c = 0; c < buffers.Length; c ++) {
                for (int b = 0; b < bytesPerSample; b ++) {
                    interLeavedBuffer[position] = buffers[c][frameStart + b];
                    position ++;
                }
            }
            frameStart += bytesPerSample;
        }
        MemoryStream bufferStream = new MemoryStream(interLeavedBuffer);
        latestMemoryStream = new WaveMemoryStream(bufferStream, format);
        latestAudioOut.Init(latestMemoryStream);
        latestAudioOut.Play();
    }
Simon Crowe
  • 105
  • 1
  • 7

2 Answers2

1

I would suppose you need to use WaveFormatExtensible instead of WaveFormat.

JeffRSon
  • 10,404
  • 4
  • 26
  • 51
0

I know this might appear to be a glib response that doesn't actually tackle your particular problem but I had a requirement to provide extensive audio support in my own project a few years ago.

After evaluating all the C# compatible libraries I could find (including NAudio) I opted to use BASS Library from Un4seen Developments This library is amazing and has full and extensive support for C#.

It can handle everything I've ever thrown at it and supports a rich plugin environment and VST support as well. Achieving what you need using BASS should be very straight forward and the support forums are very good.

Jammer
  • 9,969
  • 11
  • 68
  • 115