Resolved multithreading issue while collecting audio samples naudio

timotech

Member
Joined
Aug 15, 2022
Messages
12
Programming Experience
10+
Good day guys,

I want to collect audio samples from mic input. I can do it with the code below once, but I can't do it for multiple mic inputs

C#:
void RecordMicNAudio(int deviceNum, int t)
    {
        waveSource = new WaveInEvent();
        waveSource.DeviceNumber = deviceNum;
        waveSource.WaveFormat = new NAudio.Wave.WaveFormat(rate: sampleRate, bits: 16, channels: 1);
        waveSource.DataAvailable += (_, e) =>
        {
            // using short because 16 bits per sample is used as input wave format
            short[] samples = new short[e.BytesRecorded / 2];
            Buffer.BlockCopy(e.Buffer, 0, samples, 0, e.BytesRecorded);
            // converting to [-1, +1] range
            float[] floats = Array.ConvertAll(samples, (sample => (float)sample / short.MaxValue));
          
            //Error occurs below index out of range (t is showing 8, how come)
            realtimeSource[t].Add(new AudioSamples(floats, string.Empty, sampleRate));
                      
        };
        waveSource.RecordingStopped += (_, _) => MessageBox.Show("Sound Stopped! Cannot capture sound from device...");
        waveSource.BufferMilliseconds = 1000;
        waveSource.StartRecording();
    }
I have an array of BlockingCollection which was created using below:

C#:
BlockingCollection<AudioSamples>[] realtimeSource = new BlockingCollection<AudioSamples>[8];
That will be used to collect the samples. But the error I'm always getting is index out of range error. The below code is the code I call at the forms constructor to initialize the program:

C#:
for (int i = 0; i < realtimeSource.Length; i++)
{
     realtimeSource = new BlockingCollection<AudioSamples>();
     _ = Task.Factory.StartNew(() => RecordMicNAudio(0, i));
}
Please what I'm I missing, I've spent days on this.

NB: AudioSamples is from a library i'm using for the collection

Thanks for your help
 
Last edited by a moderator:
your suggestion worked.
Then you should mark that post as the solution and mark the thread Resolved. I've done that for you.
I'm now facing another issue.
Then you should create a new thread with all and only the information relevant to that issue and a title specifically describing that issue.

The forums are easier to use for everyone if we keep it to one topic per thread and one thread per topic.
 

Latest posts

Back
Top Bottom