Sound wave visualization with NAudio

59 Views Asked by At

I'm trying to visualize a sound wave of a recording using NAudio with C#. The code is as follows:

                // Constants
            const int SampleRate = 44100; // Sample rate (Hz)
            const int BufferSize = 1024; // Buffer size

            // Create WaveInEvent
            var waveIn = new WaveInEvent();
            waveIn.DeviceNumber = 0; // Use the default recording device
            waveIn.WaveFormat = new WaveFormat(SampleRate, 1); // Mono

            // Hook up the DataAvailable event handler
            waveIn.DataAvailable += WaveIn_DataAvailable;

            // Start recording
            waveIn.StartRecording();

            Console.WriteLine("Recording. Press any key to stop...");
            Console.ReadKey();

            // Stop recording
            waveIn.StopRecording();
            waveIn.Dispose();
        }

        // Event handler for handling incoming audio data
        private static void WaveIn_DataAvailable(object sender, WaveInEventArgs e)
        {
            // Draw audio wave using asterisks (*)
            for (int i = 0; i < e.BytesRecorded; i += 2)
            {
                short sample = (short)e.Buffer[i];
                Console.SetCursorPosition(i, sample);
                Console.Write('*');
            }
        }

It doesn't let me record a thing. It draws two asterisks and stops. I tried adding another readKey and playing around with the way I record, but it doesn't change it. What is the problem here? I don't need to improve the visualization (I doubt it's even moderately close at the moment), I just need to know why it won't let me record a thing.

0

There are 0 best solutions below