Click here to Skip to main content
15,743,541 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Dear Readers,

I am using [NAudio] to record the input from my computer. I also play it while I've written the bytes to a Wave file, I hoped there was a way to play the byte[] without having to write it first but unfortunatly there is no way to do that. Anyways, here is my code, and I would hope that you have some suggestions to make my code better because right now it works, but it's really slow. >.>

public frmMain()

        private void frmMain_Load(object sender, EventArgs e)
            // -- Create an input (Device/Stream)
            WaveIn _InputDevice = new WaveIn();

            // -- Change it to the device I want to record it from
            // - Using 1 as the default one.
            _InputDevice.DeviceNumber = 0;

            // -- Change the wave format.
            _InputDevice.WaveFormat = new WaveFormat(44100,2);

            // -- Create the event handlers.
            _InputDevice.DataAvailable += new EventHandler<WaveInEventArgs>(_InputDevice_DataAvailable);
            // -- Start recording.
            Thread _Thread = new Thread(_InputDevice.StartRecording);

        WaveFileWriter _Writer;
        void _InputDevice_DataAvailable(object sender, WaveInEventArgs e)
           // -- Get the correct path.
            string Path = Application.StartupPath + "\\" + DateTime.Now.TimeOfDay.Seconds + ".wav";

            // -- New Writer.
            _Writer = new WaveFileWriter(Path, new WaveFormat(24000, 16, 2));

            // -- Write all the bytes
            _Writer.Write(e.Buffer, 0, e.BytesRecorded);

            // -- Flush.

            // -- Close.

            // -- Play it with a sound player.
            SoundPlayer _Player = new SoundPlayer();
            _Player.SoundLocation = Path;

            // -- Delete it.

Alright, found the solution myself.
There was a method lying around the internet, took a while to find:

private void Play(byte[] p)
        WaveOut ou = new WaveOut();
        var s = new MemoryStream(p);
        RawSourceWaveStream r = new RawSourceWaveStream(s, new WaveFormat(44100, 2));
    catch { }

Share this answer
Use the BufferedWaveProvider to do this. In the DataAvailable event handler, put the data you received into the BufferedWaveProvider. Then you can have a single instance of WaveOut playing from the buffered WaveProvider all the time.
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900